Retrieve 5000+ entity records using Query Expression

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

public EntityCollection RetrieveAllContactEntityRecords(IOrganizationService _service) {
 // Declarations
 var contactFinalEntityCollection = new EntityCollection();
 EntityCollection contactEntityCollection = new EntityCollection();
 int pageNumber = 1;
 bool moreRecords = true;

// Retrive Contact Records using CRM Paging.
 while (moreRecords)
 {
 var queryExpression = new QueryExpression()
 {
 Distinct = false,
 EntityName = "contact",
 ColumnSet = new ColumnSet(true),
 Criteria = new FilterExpression
 {
 FilterOperator = LogicalOperator.And,
 Conditions =
 {
 new ConditionExpression("mobilephone", ConditionOperator.NotNull)
 }
 },
 Orders =
 {
 new OrderExpression { AttributeName = "createdon", OrderType = OrderType.Descending }
 },
 PageInfo =
 {
 Count = 5000,
 PagingCookie = (pageNumber == 1) ? null : contactEntityCollection.PagingCookie,
 PageNumber = pageNumber++
 }
 };

contactEntityCollection = _service.RetrieveMultiple(queryExpression);

if (contactEntityCollection.Entities.Count > 0)
 {
 contactFinalEntityCollection.Entities.AddRange(contactEntityCollection.Entities);
 }

moreRecords = contactEntityCollection.MoreRecords;
 }

return contactFinalEntityCollection;
 }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s