HOW TO: Using LINQ to get a Record Count in MSCRM 2011

While writing assemblies for MSCRM 2011 the chances are at some point you will want to get a record count. Its a typical check right? Perform a search on a set criteria, retrieve the record count from your search and decide what to do on the outcome of the count. Well when coding the LINQ statement to achieve this you might of noticed the Count method. However using that method will give you the following error message “The method ‘Count’ is not supported”. Strange, well I decided to check the SDK for the best way to get a count… Nothing… I decided to check the programming samples for latebinding through LINQ… Nothing…

So I will show you how I currently get a record count that doesn’t throw the “The method ‘Count’ is not supported” error. I want to demonstrate 4 LINQ statements. The first two fail on trying to get the count. You will probably be using one of these statements currently! The third statement gets you a count but its not ideal. The forth statement is the ideal way in which I am currently getting record counts. In these samples OrgService is the OrganizationServiceContext object.

var query = from a in OrgService.CreateQuery("account")
select a;

var count = query.Count();

Fails with “The method ‘Count’ is not supported”, when var for the LINQ query is used. The variable query resolves to IQuerable<>

var count = (from a in OrgService.CreateQuery("account")
select a).Count();

Again fails with “The method ‘Count’ is not supported”. I thought setting the query up in this manor would use IEnumerable<> instead of IQuerable<>.

var query = from a in OrgService.CreateQuery("account")
select a;

var count = query.ToList().Count;

This method works but it is not ideal as I am starting with IQuerable<> then converting to IEnumerable<> to get the count.

IEnumerable query = from a in OrgService.CreateQuery("account")
select a;

var count = query.Count();

This is the ideal solution. Define the LINQ query’s return as IEnumerable<> and then get the count.

Leave a Reply

Your email address will not be published. Required fields are marked *