web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Blogs / Pablo Peralta's Blog / TIP: How to easily workarou...

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

Pablo Peralta Profile Picture Pablo Peralta 793

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.

Comments

*This post is locked for comments