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

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 !

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

  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”


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s