A bit of Syntatic Sugar for Dynamics CRM 2011 LINQ

Gayan Perera, 11 October 2010

A bit of Syntatic Sugar for Dynamics CRM 2011 LINQWe've been using XrmLinq for our Dynamics CRM 4.0 developments and we've gotten use to that syntax, the new LINQ provider in Dynamics CRM 2011 is a bit different but thanks to extension methods and generics we can make it look the same as XrmLinq. The main reason for this is to port existing code over to Dynamics CRM 2011 with minimal efforts.

*

For example, a dynamic query which returns a list of accounts in Dynamics CRM 2011 will look like this:

OrganizationServiceContext context = new OrganizationServiceContext(service);
var accounts = (from a in context.CreateQuery("account")
                where ((string)a["name"]).StartsWith("Microsoft")
                select new
                {
                    Id = (Guid)a["accountid"],
                    Name = (string)a["name"]
                }).ToList();

With the extension methods (see below), the query looks like this:

XrmDataContext xrm = new XrmDataContext(service);
var results = (from a in xrm["account"]
                where a.Attribute<string>("name").StartsWith("Microsoft")
                select new
                {
                    Id = a.Attribute<Guid>("accountid"),
                    Name = a.Attribute<string>("name")
                }).ToList(); 

XrmDataContext class:

public class XrmDataContext : OrganizationServiceContext
{
    private IOrganizationService _service = null;
 
    public XrmDataContext(IOrganizationService service) 
    : base (service) 
    {
        _service = service;
    }
 
    public virtual IQueryable<Entitythis[string entityName]
    {
        get { return this.CreateQuery(entityName); }
    }
}
 
public static class XrmExtensions
{
    public static T Attribute<T>(this Entity entity, string schemaName)
    {
        if (entity.Contains(schemaName)) { return (T)entity[schemaName]; }
        return default(T);
    }
}

*Image from http://landanimal.files.wordpress.com/2010/06/sugar.jpg