CRM 2015 Linq Count() query - is this enumerating the query?

折月煮酒 提交于 2019-12-12 13:18:08

问题


I've been struggling with writing Linq queries against the Dynamics CRM 2015 SDK OrganizationServiceContext. I'm finding that often the Linq methods I want to use are not supported by the CRM Linq Provider.

The latest is Count(). I have an IQuerable<Lead> object and want to count the total records that would be returned when enumerated. But calling Count() on an IQueryable gives the error:

The method 'Count' is not supported

Digging around I found this advice which is to define the Linq query as an IEnumerable. This appears to work - calling Count() on the IEnumerable<Lead> object returns the total records.

What I'd like to know is where the enumeration operation takes place. Is it Dynamics side, or is it pulling all leads into my web server memory and counting there? The whole reason I'm performing the count in the first place is to guard against pulling too large a dataset into memory...


回答1:


LINQ for CRM queries are translated to QueryExpression queries and therefore are limited to its capabilities. QueryExpression queries do not support aggregates (like count, sum, average), so indeed your query will pull all selected records into memory.

The preferred method to get a proper count is using a FetchXml query.

A count with QueryExpression can also be achieved in the following way. (I am not sure how this is translated into SQL; it may be slightly less performant.)

Here an example:

var query = new QueryExpression("account")
{
    PageInfo = new PagingInfo
    {
        Count = 1,
        PageNumber = 1,
        ReturnTotalRecordCount = true
    }
};

var result = service.RetrieveMultiple(query);

if (result.TotalRecordCountLimitExceeded)
    throw new InvalidOperationException("Cannot get record count.");

return result.TotalRecordCount;

As you can see, there is a limit for the number of records that can be counted. I believe it currently is 50,000. In OnPremise deployments you can configure this limit.



来源:https://stackoverflow.com/questions/31559467/crm-2015-linq-count-query-is-this-enumerating-the-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!