如何从CRM中获取超过5000个实体

我从我的控制台应用程序查询MS Dynamics CRM Online:

public EntityCollection GetEntities(string entityName) { IOrganizationService proxy = ServerConnection.GetOrganizationProxy(); string request = string.Format("", entityName); FetchExpression expression = new FetchExpression(request); var mult = proxy.RetrieveMultiple(expression); return mult; } 

此代码仅在mult.Entities返回最多5000个元素。 我知道CRM中有更多实体。 如何检索所有的entites?

您只能使用fetch XML一次返回5000条记录。

要获得更多记录,您必须使用分页cookie,请参阅此处:

示例:将FetchXML与分页cookie一起使用

代码的相关部分:

 // Define the fetch attributes. // Set the number of records per page to retrieve. int fetchCount = 3; // Initialize the page number. int pageNumber = 1; // Specify the current paging cookie. For retrieving the first page, // pagingCookie should be null. string pagingCookie = null; 

修改了主循环,因为样本似乎没有更新分页cookie:

 while (true) { // Build fetchXml string with the placeholders. string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount); FetchExpression expression = new FetchExpression(xml); var results = proxy.RetrieveMultiple(expression); // * Build up results here * // Check for morerecords, if it returns 1. if (results.MoreRecords) { // Increment the page number to retrieve the next page. pageNumber++; pagingCookie = results.PagingCookie; } else { // If no more records in the result nodes, exit the loop. break; } } 

我个人倾向于使用LINQ而不是FetchXML,但值得注意的是Lasse V. Karlsen所说的,如果你向用户提供这些信息,你可能想做某种分页(在FetchXML或LINQ中)

您可以使用LINQ,如下所示。 CRM LINQ提供程序将自动分页查询并运行获取完整结果所需的尽可能多的请求,并在单个对象中返回完整集。 这对我们来说真的很方便。 但是,要小心。 如果结果集非常大,则会明显变慢,甚至在极端情况下甚至会抛出OutOfMemoryException。

  public List GetEntities(string entityName) { OrganizationServiceContext DataContext = new OrganizationServiceContext(ServerConnection.GetOrganizationProxy()); return DataContext.CreateQuery(entityName).toList(); } 

这是使用FetchXML进行分页的另一种实现,我比官方示例更喜欢它:

 int page = 1; EntityCollection entityList = new EntityCollection(); do { entityList = Context.RetrieveMultiple(new FetchExpression(String.Format(" ... ", SecurityElement.Escape(entityList.PagingCookie), page++))); // Do something with the results here } while (entityList.MoreRecords); 

我遇到过同样的问题。 我通过在fetch xml或Query Expression中包含实体的id来解决它。 如果您在查询中包含传递“lead”,那么还要添加“leadid”。 然后为您自动生成分页cookie。