Retrieve 5000+ records using FetchXML and Query Expression

In my previous post, explained how to Retrieve 5000+ entity records using Query Expression,

In this post, will explain how to Retrieve 5000+ entity records using FetchXML and Query Expression.

Example: Retrieve All contact records where MobilePhone data is not null.

use below method,

public static EntityCollection RetrieveAllRecordsUsingFetchXML(IOrganizationService service, string fetchXML)
 {
 var moreRecords = false;
 int page = 1;
 var cookie = string.Empty;
 var entityCollection = new EntityCollection();
 do
 {
 var xml = string.Format(fetchXML, cookie);
 var collection = service.RetrieveMultiple(new FetchExpression(xml));

if (collection.Entities.Count > 0) entityCollection.Entities.AddRange(collection.Entities);

moreRecords = collection.MoreRecords;
 if (moreRecords)
 {
 page++;
 cookie = string.Format("paging-cookie='{0}' page='{1}'", System.Security.SecurityElement.Escape(collection.PagingCookie), page);
 }
 Console.WriteLine(entityCollection.Entities.Count);
 } while (moreRecords);

return entityCollection;
 }

Get the required FetchXML from CRM Advanced Find and format using FetchXML Formatter Online.

For the example stated above, required FetchXML is as follows,

string fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' {0}>" +
" <entity name='contact'>" +
" <attribute name='fullname' />" +
" <attribute name='mobilephone' />" +
" <attribute name='contactid' />" +
" <order attribute='fullname' descending='false' />" +
" <filter type='and'>" +
" <condition attribute='mobilephone' operator='not-null' />" +
" </filter>" +
" </entity>" +
"</fetch>";

Note: Do not forget to append {0} in the first line of the formatted FetchXML.

How to Call Method?

EntityCollection contactCollection = RetrieveAllRecordsUsingFetchXML(_orgService, fetchXML);
Inspired from MS Dynamics CRM – Tips from a Developer Blog
Advertisements