通过C#检索CRM中所有帐户的列表?

我正在尝试从CRM 2011中检索所有帐户记录,以便我可以使用ForEach循环遍历它们并填充下拉列表。 我正在阅读这篇文章( 检索实体列表 ),并且能够检索满足特定条件的所有帐户,但我如何检索所有? 这是每一个账户记录,无论条件如何?

这是我正在使用的代码,但我不知道在context.AccountSet之后使用哪种方法。 获得所有帐户。

var context = new XrmServiceContext(); var parentAccount = context.AccountSet.All(snippet => snippet.ParentAccountId == "Account1"); 

使用context.AccountSet.All我可以获得符合条件的所有记录,但我真的不需要条件……

谢谢你的帮助!

为什么不检索与下拉相关的内容?

Account有许多属性只会使查询膨胀。

 /* If you only want name */ var accounts = context.AccountSet.Select(acc => acc.Name); /* If you want more attributes */ var accounts = context.AccountSet .Select(acc => new { name = acc.Name, guid = acc.AccountId, parent = acc.ParentAccountId, number = acc.AccountNumber }); /* No need to call .ToList() on accounts, just iterate through the IQuerable */ foreach (var account in accounts) { // Add account to drop down } 

AccountSet已包含所有记录,这就是为什么如果你执行.ToList()得到一个Account of List ,因为你将AccontSet集合转换为List。

试试这个:

 var parentAccount = (from c in context.CreateQuery() select c); 

如果它没有返回正确的类型而不是var use

 IEnumerable 

您可能还需要包含

 using System.Linq; 

首先,您应该与CRM建立连接。通过CRMConnection类或最新的CRM 2016连接方法。 下方链接。 https://msdn.microsoft.com/en-in/library/jj602970.aspx

建立连接后。 您可以使用QueryExpression类查询实体并将整个数据存储在ColumnSet中,ColumnSet是一组列,顾名思义。 此代码将crm中的帐户名和ID存储到单个列表中。 请注意,columnset采用字符串参数,因此可以将columnname的字符串数组传递给它。 谢谢,如果您有疑问,请告诉我。

  QueryExpression query = new QueryExpression("account"); query.ColumnSet.AddColumns("name","accountid"); // query.Criteria.AddFilter(filter1); EntityCollection result1 = service.RetrieveMultiple(query); Console.WriteLine(); Console.WriteLine("Query using Query Expression with ConditionExpression and FilterExpression"); Console.WriteLine("---------------------------------------"); foreach (var a in result1.Entities) { //Console.WriteLine("Name: " + a.Attributes["name"]); ListAccountName.Add(a.Attributes["name"].ToString()); ListAccountId.Add(a.Attributes["accountid"].ToString()); }