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
- Created a console application
-
From the Main method, called the two methods:
- RetrieveMultiple: It will use the Service.RetrieveMultiple request
- RetrieveMultipleRequest: It will use the RetrieveMultipleRequest message
-
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
- Use the RetrieveMultipleRequest message
- Add a do...while loop based on the MoreRecords property of the entity collection
- 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
Post a Comment