CRM2011 and C# : Avoiding the 5000 records limitation. Paging Retrieve Multiple Results.

As most of you will know when querying the CRM using RetrieveMultiple command there is a limitation of 5000 records that, when creating processes that afect a large number of rows, can´t be a real pain.

There are some ways of changing this limitation by touching the server registry or changing some SQL server values in the MSCRM_CONFIG Database as described in the following post, but here is a great solution to do it programatically without changing any configuration value.

Programatically using RetrieveMultipleRequest and RetrieveMultipleReponse.

 public EntityCollection GetAllLeads(OrganizationService service)
            EntityCollection exit = new EntityCollection();

                QueryExpression queryServicios = new QueryExpression
                    EntityName = "lead",
                    ColumnSet = new ColumnSet("leadid", "statecode", "statuscode"),
                    Criteria = new FilterExpression()

                queryServicios.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);

                int pageNumber = 1;
                RetrieveMultipleRequest multiRequest;
                RetrieveMultipleResponse multiResponse = new RetrieveMultipleResponse();

                    queryServicios.PageInfo.Count = 5000;
                    queryServicios.PageInfo.PagingCookie = (pageNumber == 1) ? null : multiResponse.EntityCollection.PagingCookie;
                    queryServicios.PageInfo.PageNumber = pageNumber++;

                    multiRequest = new RetrieveMultipleRequest();
                    multiRequest.Query = queryServicios;
                    multiResponse = (RetrieveMultipleResponse)service.Execute(multiRequest);

                while (multiResponse.EntityCollection.MoreRecords);

            catch (Exception ex)
                log = new Logger(";;" + ex.Message);


            return exit;

To do paging using Fetch XML.

Hope it helps. Have a nice day.



2 thoughts on “CRM2011 and C# : Avoiding the 5000 records limitation. Paging Retrieve Multiple Results.

Leave a Reply

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

You are commenting using your 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