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)
result.Add(item);
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:
- Microsoft added support for Linq in their xRM framework of the Advanced Developer Extensions.
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.
