Retrieve more than 5000 records in Dynamics 365


We know there is limitation that by default we can get maximum 5000 records in a single web service call but by using paging cookie concept we can get more then 5000 records. Sharing sample code how to use it.

public static List<StudentRecord> ReturnStudentListTest(IOrganizationService service, Int16 pageNumber, Int16 fetchCount)
{
List<StudentRecord> StudentList = new List<StudentRecord>();
string fetchStudent = string.Empty;
string pagingCookie = null;

if (fetchCount == 0)
{
fetchCount = 100;
}
if (pageNumber == 0)
{
pageNumber = 1;
}

fetchStudent = “<fetch version=’1.0′ output-format=’xml-platform’ mapping=’logical’ distinct=’true’>” +
” <entity name=’contact’>” +
” <attribute name=’contactid’ />” +
” <attribute name=’fullname’ />” +
” <order attribute=’fullname’ descending=’false’ />” +
” <filter type=’and’>” +
” <condition attribute=’statecode’ operator=’eq’ value=’0′ />” +
” </filter>” +
” </entity>” +
“</fetch>”;

while (true)
{
string fetchXmlWithPaging = Helper.CreateXml(fetchStudent, pagingCookie, pageNumber, fetchCount);
var fetchExpression = new FetchExpression(fetchXmlWithPaging);
EntityCollection studentCollection = service.RetrieveMultiple(fetchExpression);
if (studentCollection.Entities.Count > 0)
{
foreach (var record in studentCollection.Entities)
{
try
{
StudentRecord studentRecord = new StudentRecord();
studentRecord.studentId = record.Contains(CRMConstants.Contact.studentId) ? ((Guid)record.Attributes[CRMConstants.Contact.studentId]).ToString() : string.Empty;
studentRecord.fullname = record.Attributes.Contains(CRMConstants.Contact.fullname) ? record.Attributes[CRMConstants.Contact.fullname].ToString().ToUpper() : String.Empty;
StudentList.Add(studentRecord);
}
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
{
throw new Exception(ex.Detail.Message);
}
catch (Exception ex)
{
throw new InvalidCastException(ex.Message);
}
}
if (studentCollection.MoreRecords)
{
pageNumber++;
pagingCookie = studentCollection.PagingCookie;
}
else
break;
}
}
return StudentList;
}

Please refer the below URL for details.
https://msdn.microsoft.com/en-us/library/mt269606.aspx
https://softchief.com/2016/02/20/retrieve-more-than-5000-records-in-dynamics-crm/

Hope it helps.

%d bloggers like this: