2015-04-22 107 views
2

您好我想从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); 
     } 

回答

3

访问之前,你要问,如果它是在上下文中的属性:

e.Attributes.Contains("address1_city") 

如果集合包含属性,那么你就可以访问它的安全。

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

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

+0

感谢您的帮助。我有一个对象类型的属性,我无法从该属性获取值。正如你的代码中所提到的,我可以检查并检索address1_city,因为它是字符串类型,但是我还有一个属性状态是哪个对象类型。我试图检查并检索它,但无法做到这一点。请建议 – user2897967

+0

如果您有像“状态码”这样的属性,则必须将其转换为“OptionSetValue” – Sxntk

1

当检索到后期绑定的对象的属性值时,建议的方法是使用方法getAttributeValue<T>。如果该属性不存在于实体的属性集合中,则返回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.g.以下代码行有效:

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

您必须注意getAttributeValue 返回的默认值。当键不存在时,处理默认值时处理该做什么更好。 – Sxntk

+1

我不同意。遵循这种方法将很快使您的代码变得冗长而难以阅读和维护。在大多数情况下,使用可空类型可以很好地完成这项工作。 –

+0

DateTime,decimal和bool的默认值不为空 – Sxntk

相关问题