Tsc*_*eck 8 c# dynamics-crm-online dynamics-crm-2013
我从我的控制台应用程序查询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;
}
Run Code Online (Sandbox Code Playgroud)
此代码仅返回最多5000个元素mult.Entities.我知道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;
Run Code Online (Sandbox Code Playgroud)
修改了主循环,因为样本似乎没有更新分页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;
}
}
Run Code Online (Sandbox Code Playgroud)
我个人倾向于使用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();
}
Run Code Online (Sandbox Code Playgroud)
这是使用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);
Run Code Online (Sandbox Code Playgroud)