Mixing early-binding and late-binding with nameof operator in C# [CRM]

There are many benefits of using early-binding when coding against CRM. There are times however when you need to fall back to late-binding, for example when you need to query relationships, or when you need to call Retrieve to optimise performance (as this service call allows you to load only selected fields of a record).

Rather than using literal string, you can use the nameof operator in C# 6 to get the attributes and relationship names. This works because the properties of the early-binding classes are generated based on the attributes and relationship names in CRM.

For example, to get the AccountNumber field of an Account record:

var client = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CRM"].ConnectionString);

//Remember to convert to lowercase.
var accountNumberAttributeName = nameof(Account.AccountNumber).ToLower();

var entity = client.Retrieve(Account.EntityLogicalName, Guid.NewGuid(), new ColumnSet(accountNumberAttributeName));
var accountNumber = entity.ToEntity<Account>().AccountNumber;

And there you have it: late-binding with all the early-binding zen!

About Bernado

Based in Australia, I am a freelance SharePoint and Dynamics CRM developer. I love developing innovative solutions that address business and everyday problems. Feel free to contact me if you think I can help you with your SharePoint or CRM implementation.
This entry was posted in CRM. Bookmark the permalink.

2 Responses to Mixing early-binding and late-binding with nameof operator in C# [CRM]

  1. Nishant Rana says:

    Reblogged this on Nishant Rana's Weblog and commented:
    nameof expression in C#6.0

  2. I have been using below function to achieve this prior to C# 6, now it is very easy using nameof, thanks for sharing

    public string NameOf(Expression<Func> memberExpression)
    {
    MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
    return expressionBody.Member.Name.ToLowerInvariant();
    }

Leave a comment