Get Total Count of records in CRM. (more than 5000)

For version 9.0 please check the below post


Just sharing a sample code to get the total number of records (e.g. account here)

 IOrganizationService orgService = GetOrganizationService();

 int totalCount = 0;

 QueryExpression query = new QueryExpression("account");
 query.ColumnSet = new ColumnSet();
 query.Distinct = true;
 query.PageInfo = new PagingInfo();
 query.PageInfo.Count = 5000;
 query.PageInfo.PageNumber = 1;
 query.PageInfo.ReturnTotalRecordCount = true;

 EntityCollection entityCollection = orgService.RetrieveMultiple(query);
 totalCount = entityCollection.Entities.Count;

 while (entityCollection.MoreRecords)
 query.PageInfo.PageNumber += 1;
 query.PageInfo.PagingCookie = entityCollection.PagingCookie;
 entityCollection = orgService.RetrieveMultiple(query);
 totalCount = totalCount + entityCollection.Entities.Count;



Hope it helps

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

4 thoughts on “Get Total Count of records in CRM. (more than 5000)”

    1. Thanks ! It would fail in case of more that 50000 records
      System.ServiceModel.FaultException`1: ‘AggregateQueryRecordLimit exceeded. Cannot perform this operation.’


  1. it’s work on account Entity
    i change the QueryExpression to other Entity,
    when i got the error “Paging cookie is required when trying to retrieve a set of records on any high pages”


Please share your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.