DYNAMICS 365 HOW TO RETRIEVE MORE THAN 5000 RECORDS IN C#

In this post, you will see how to retrieve more than 5000 records from CRM/D365 entities in C#.

To do this, I imported thousands of records into the contact entity

  1. Created a console application
  2. From the Main method, called the two methods:
    • RetrieveMultiple: It will use the Service.RetrieveMultiple request
    • RetrieveMultipleRequest: It will use the RetrieveMultipleRequest message
  3. Ran the console application that will give the below result
The RetrieveMultiple method is limited to retrieve 5000 records maximum and will look as follows.

public string RetrieveMultiple()
{
EntityCollection objCollection = new EntityCollection();
QueryExpression objQuery = new QueryExpression
{
EntityName = "contact",
ColumnSet = new ColumnSet(new String[] { "firstname", "lastname", "emailaddress1" }),
};
return CRMService.RetrieveMultiple(objQuery).Entities.Count.ToString();
}



In order to retrieve more than 5000 records, we have to apply the following
  1. Use the RetrieveMultipleRequest message
  2. Add a do...while loop based on the MoreRecords property of the entity collection
  3. In each iteration, we have to increase the PageNumber property

The full method using the RetrieveMultipleRequest will look as follows.

public string RetrieveMultipleRequest()
{
EntityCollection objCollection = new EntityCollection();
QueryExpression objQuery = new QueryExpression
{
EntityName = "contact",
ColumnSet = new ColumnSet(new String[] { "firstname", "lastname", "emailaddress1" }),
};

int pageNumber = 1;
RetrieveMultipleRequest objRequest;
RetrieveMultipleResponse objResponse = new RetrieveMultipleResponse();
do
{
objQuery.PageInfo.Count = 5000;
objQuery.PageInfo.PagingCookie = (pageNumber == 1) ? null : objResponse.EntityCollection.PagingCookie;
objQuery.PageInfo.PageNumber = pageNumber++;
objRequest = new RetrieveMultipleRequest();
objRequest.Query = objQuery;
objResponse = (RetrieveMultipleResponse)CRMService.Execute(objRequest);
objCollection.Entities.AddRange(objResponse.EntityCollection.Entities);
}
while (objResponse.EntityCollection.MoreRecords);
return objCollection.Entities.Count.ToString();
}


Hope This Helps!

Comments

Popular posts from this blog

DYNAMICS 365 FILTER LOOKUP FIELD BASED ON N:N RELATIONSHIP

DYNAMICS 365 LEVEL UP BROWSER EXTENSION - PART 1 - FORMS

DYNAMICS 365 REFERENCE PANEL