字典查找CRM C#插件中没有给定的键

时间:2017-09-13 07:47:40

标签: c# plugins dynamics-crm

我有使用C#从CRM插件中的Lookup中检索值的代码。它很简单,从查找读取guid然后在异常中显示它。

//Get ParentCaseID
Guid HeaderId = ((EntityReference)entity["new_LookupTransactionHeader"]).Id;

throw new InvalidPluginExecutionException(HeaderId.ToString());

在这段代码中,我只想从查找中获取guid,但是当我运行插件时,我得到了这样的错误。

  

字典中没有给定的密钥

3 个答案:

答案 0 :(得分:3)

使用entity["attribute"]索引器访问基础Attribute属性,该属性是AttributeCollection对象,其行为与Dictionary<string, object>非常相似。

在这种情况下,字典不包含您的密钥new_LookupTransactionHeader - 这可能是因为您查询了CRM中的数据,并且CRM中的值为null,在这种情况下CRM省略字典中的值(即使您在ColumnSet中特别请求了它)。

您可以在尝试访问密钥之前检查密钥是否存在于字典中,例如entity.Attributes.HasKey("new_LookupTransactionHeader")

您也可以使用entity.GetAttributeValue<EntityReference>("new_LookupTransactionHeader"),如果密钥不存在,则返回null(而不是抛出异常。

答案 1 :(得分:1)

代码应该是自我解释的:

if(entity.Contains("new_LookupTransactionHeader")){
  Guid HeaderId = ((EntityReference)entity["new_LookupTransactionHeader"]).Id;
  throw new InvalidPluginExecutionException(HeaderId.ToString());
}
else
{
  throw new InvalidPluginExecutionException("There is no value in field new_LookupTransactionHeader.");
}

答案 2 :(得分:1)

Guid HeaderId; 

if (entity.Attributes.Contains("new_LookupTransactionHeader"))
{
 Guid HeaderId= ((EntityReference)entity["new_LookupTransactionHeader"]).Id; 
}

其余的可以自己添加,如果contains返回false,则它不存在