Paging Queries in Dynamics CRM 2011

As you may already know, Dynamics CRM 2011 has a limit of retrieving 5000 records when executing a RetrieveMultiple request. For systems where a large number of records need to be retrieved, a paging technique needs to be used when writing queries. The Microsoft Dynamics CRM 2011 SDK provides a simple mechanism for writing such queries. Let’s assume I have a large Contact database consisting of 100,000 records. To retrieve all of these Contacts, I can use the following query:

int pageNumber = 1;
bool moreRecords = true;    // we want to loop through at least once
List contacts = new List();

while (moreRecords)
    QueryExpression query = new QueryExpression { EntityName = "contact" };
    query.PageInfo = new PagingInfo
        PageNumber = pageNumber,
        Count = 5000

    EntityCollection results = sdk.RetrieveMultiple(query);
    contacts.AddRange(results.Entities.ToList());   // add to our list of contacts
    moreRecords = results.MoreRecords;

    if (moreRecords)

The code will query CRM 20 times until it has all 100,000 contact records in the list. The query will return “moreRecords = false” in which case it will exit the loop and stop querying CRM.

I hope this helps!


Leave a Reply

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