字典中不存在给定的键

The given key is not present in the dictionary

您好,我正在尝试从 CRM 2011 中获取帐户。我正在获取 EntityCollection 中的数据。但是,当我尝试从 entityCollection 读取或访问数据时,它显示了第一条记录,但在该记录之后抛出了错误。请查看下面的代码并向我提出建议。

  string fetch2 = @"
                          <fetch version='1.0' output-format='xml-platform'      mapping='logical' distinct='false'>
      <entity name='account'>
      <attribute name='name' />
      <attribute name='address1_city' />
      <attribute name='primarycontactid' />
      <attribute name='telephone1' />
      <attribute name='accountid' />
      <order attribute='name' descending='false' />
      <filter type='and'>
         <condition attribute='accounttype' operator='eq' value='01' />
     </filter>
     </entity>
     </fetch>";

        try
        {
            EntityCollection fxResult = _service.RetrieveMultiple(new  FetchExpression(fetch2));
            foreach (var e in fxResult.Entities)
            {
                Console.WriteLine("Id:{0},Name:{1},City:{2}", e.Attributes  ["accountid"].ToString(), e.Attributes["name"].ToString(), e.Attributes["address1_city"].ToString());
               // Console.WriteLine("Id:{0},Name:{1},City:{2}", e.ToEntity["accountid"]);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Error:==" + e.Message);
        }

在访问属性之前,您需要询问它是否在上下文中:

e.Attributes.Contains("address1_city")

如果集合包含该属性,那么您可以安全地访问它。

string accountid = (string)e.Attributes["address1_city"]

属性没有出现在集合中的原因是它为空或者您没有检索它。在这种情况下,您的属性之一可能为空。也许 address1_city.

检索后期绑定 Entity 对象的属性值时,推荐的方法是使用方法 getAttributeValue<T>。当属性不存在于实体的属性集合中时,它 returns default(T).

记录的主键 ('id') 在 OrganizationService 返回时始终存在。

因此您的代码应如下所示:

EntityCollection fxResult = _service.RetrieveMultiple(new FetchExpression(fetch2));

foreach (var e in fxResult.Entities)
{
    Console.WriteLine(
        "Id:{0},Name:{1},City:{2}",
        e.Id,
        e.GetAttributeValue<string>("name"),
        e.GetAttributeValue<string>("address1_city"));
}

当您需要为属性赋值时,您可以安全地使用项目选择器,无论它是否已经存在。

例如以下代码行有效:

e["name"] = "Demo Accountname";