Tuesday, October 23, 2018

D365 - Retreive more than 5000 records using fetchxml

 private static List RetrieveAllRecords(IOrganizationService service, string fetch)  
     {  
       var moreRecords = false;  
       int page = 1;  
       var cookie = string.Empty;  
       List<Entity> Entities = new List();  
       do  
       {  
         var xml = string.Format(fetch, cookie);  
         var collection = service.RetrieveMultiple(new FetchExpression(xml));  
         if (collection.Entities.Count >= 0) 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);  
         }  
       } while (moreRecords);  
       return Entities;  
     }  

Usage

  var fetch = "<fetch {0}>" +  
             "  <entity name='accounts' >" +  
             "    <attribute name='accountid' />" +  
             "    <attribute name='name' />" +  
             "  </entity>" +  
             "</fetch>";  
       var accountCol = RetrieveAllRecords(service, fetch);