A bit of syntatic sugar for CRM 2011 LINQ

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

For example, a dynamic query which returns a list of accounts in 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);
    }
}

1 Comment

Comments have been disabled for this content.