Type-safe Queries in Dynamics CRM 4

Avoiding string literals and writing type-safe code as supported by the compiler are among my favorite code-writing philosophies.

So when I started to work on a Dynamics CRM project, which by default uses strings for table and column names (fortunately, table names can be accessed by the EntityNames enumeration), I wished there was a Linq-like way to access the CRM Service.

Therefore, the first code I wrote was a method implementing a type-safe query encapsulating RetrieveMultiple():

public static List<T> RetrieveMultiple<T>(this CrmService service) 
  where T : BusinessEntity
  List<T> result = new List<T>();

  QueryExpression query = new QueryExpression();
  query.EntityName = typeof(T).Name;      
  query.ColumnSet = new AllColumns();

  BusinessEntityCollection retrieved = service.RetrieveMultiple(query);
  foreach (T item in retrieved.BusinessEntities)

  return result;

While not very powerful and flexible, this method provides both type-safe compilablity and avoidance of string literals.

After some research, I found that there are already libraries supporting Linq queries for Dynamics CRM:

These libraries come with an overhead though:

  • LINQtoCRM requires all queries to be created through its CrmQueryProvider class.
  • xRM provides Linq queries through its XrmDataContext class which requires a connection string in the .config file and generating DTOs using CrmSvcUtil.

Both options may be challenging to include in an already existing project.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: