When using early bound entities, there’s a easy way to get CRM entity logical attribute name thanks to AttributeLogicalNameAttribute attribute in generated code. You can use this simple extension method:
public static string GetEntityPropertyLogicalName<E, P>(this E src, Expression<Func<E, P>> expression)
{
var member = expression.Body as MemberExpression;
if (member != null && member.Member is PropertyInfo)
{
var pi = member.Member as PropertyInfo;
var pn = pi.Name;
var epi = typeof(E).GetProperty(pn);
var attr = (AttributeLogicalNameAttribute) epi.GetCustomAttribute(typeof(AttributeLogicalNameAttribute));
if (attr == null)
{
throw new System.ArgumentNullException(pn, "AttributeLogicalNameAttribute not found on property");
}
return attr.LogicalName;
}
throw new ArgumentException("Expression is not a Property");
}
And usage is very simple:
var account = new Account();
var line1 = account.GetEntityPropertyLogicalName(p => p.Address1_Line1);
Now line1 should contain address1_line1 string.