[英]How to fetch more than 5000 entities from CRM
我從我的控制台應用程序查詢MS Dynamics CRM Online:
public EntityCollection GetEntities(string entityName)
{
IOrganizationService proxy = ServerConnection.GetOrganizationProxy();
string request = string.Format("<fetch mapping ='logical'><entity name = '{0}'></entity></fetch>", entityName);
FetchExpression expression = new FetchExpression(request);
var mult = proxy.RetrieveMultiple(expression);
return mult;
}
此代碼僅在mult.Entities
返回最多5000個元素。 我知道CRM中有更多實體。 如何檢索所有的entites?
您只能使用fetch XML一次返回5000條記錄。
要獲得更多記錄,您必須使用分頁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<Entity> 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("<fetch version='1.0' page='{1}' paging-cookie='{0}' count='1000' output-format='xml-platform' mapping='logical' distinct='false'> ... </fetch>", SecurityElement.Escape(entityList.PagingCookie), page++)));
// Do something with the results here
}
while (entityList.MoreRecords);
我遇到過同樣的問題。 我通過在fetch xml或Query Expression中包含實體的id來解決它。 如果您在查詢中包含傳遞“lead”,那么還要添加“leadid”。 然后為您自動生成分頁cookie。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.