CRM SDK Nugget: Entity.ToEntityReference Method

Here is another cool Entity extension method that I keep forgetting to use: Entity.ToEntityReference.

Normally, when creating a reference to an Entity, we would use something like this:

RetrieveRequest request2 = new RetrieveRequest
{
    Target = new EntityReference(Account.EntityLogicalName, account2.Id),
    ColumnSet = new ColumnSet(),
    RelatedEntitiesQuery = new RelationshipQueryCollection()
};

However, if we have already gone to the trouble of creating or retrieving a record from CRM, we can just use .ToEntityReference, like this:

RetrieveRequest request = new RetrieveRequest
{
    Target = account.ToEntityReference(),
    ColumnSet = new ColumnSet(),
    RelatedEntitiesQuery = new RelationshipQueryCollection()
};

 

It’s a small change, but one that does make your code a little more readable.

Leave a Reply 1 comment