Dynamics CRM: Use paging to manage query results – C#

I have already talked about the search result limitations OOB of Dynamics CRM in this blogpost. In that blogpost I talked about various ways to override the limit in CRM and SQL, both methods are not really recommnded by Msft, there is a reason for OOB limitation, the preferred method is to do paging in your code. Now I want to talk about how to override the limitation in C#, this can be used in your MIM ECMA code when you read from Dynamics CRM.

FetchXML is one way to do this paging in Dynamics CRM but I found a much simpler way to do it.

After you declare your Queryexpression and the column sets or conditions that you want declare PageInfo instance and then set the following parameters on the PageInfo

  • Count per page
  • Pagenumber to start

Thats  all you really need

Sample code

EntityCollection GetAllContacts;

QueryExpression query = new QueryExpression
EntityName = Contact.EntityLogicalName,
ColumnSet = new ColumnSet(true)

query.PageInfo = new PagingInfo();
query.PageInfo.Count = 1000;
query.PageInfo.PageNumber = 1;
query.PageInfo.ReturnTotalRecordCount = true;
EntityCollection myContacts = _service.RetrieveMultiple(query);
GetAllContacts = myContacts;

while (myContacts.MoreRecords)
query.PageInfo.PageNumber += 1;
query.PageInfo.PagingCookie = myContacts.PagingCookie;
myContacts = _service.RetrieveMultiple(query);
//Add to the collection
foreach (Entity e in myContacts.Entities)

foreach (Entity contact in GetAllContacts.Entities)
if (contact.Contains(“fullname”))
Console.WriteLine(“Contact Name = ” + contact[“fullname”]);
if (contact.Contains(“firstname”))
Console.WriteLine(“Contact Name = ” + contact[“firstname”].ToString());