TIP: How to easily workaround “The method 'Count' is not supported”

Hi,

I came across this problem when running a LINQ query through Dynamics CRM LINQ provider for getting the count of records returned by my query.

My query looked like this:

 

var lineItems = from lineItem in MyXrmServiceContext.OpportunityProductSet
                         where lineItem.OpportunityId.Id == opportunityId
                         select lineItem;
 
 if (lineItems != null && lineItems.Count() > 0)
 {
     foreach (OpportunityProduct lineItem in lineItemsToDelete)
     {
         //do something
     }
 }

 

Unfortunately this simple statement (lineItems.Count()) throws the following exception:

 

The method ‘Count’ is not supported

 

I have made some research and found some ways to workaround it by using FetchXml or RetrieveMultiple to get the count of records. Nevertheless, I discovered another workaround much simpler I guess that could perfectly work in case you are working with few records (I think it may be not so performant with relevant amount of records). The approach is just converting the IQueryable collection to a List, as shown below:

 

var lineItems = from lineItem in MyXrmServiceContext.OpportunityProductSet
                         where lineItem.OpportunityId.Id == opportunityId
                         select lineItem;
 
 if (lineItems != null && lineItems.ToList<OpportunityProduct>().Count() > 0)
 {
     foreach (OpportunityProduct lineItem in lineItemsToDelete)
     {
         //do something
     }
 }

 

Now, getting the count of records works like a charm for me Smile.

 

Hope it helps you in your developments,

 

PP [twitter: @pabloperalta]

UruIT Dynamix | Excellence in Dynamics CRM Nearshoring Services.

uruit_dynamix_016[2]

4 Comments

Comments have been disabled for this content.