【问题标题】:the given key was not present in the dictionary lookup CRM C# Plugin字典查找 CRM C# 插件中不存在给定的键
【发布时间】:2018-02-21 19:48:16
【问题描述】:

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

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

throw new InvalidPluginExecutionException(HeaderId.ToString());

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

给定的键不在字典中

【问题讨论】:

  • 一些问题:new_LookupTransactionHeader 是查找字段的正确大写的逻辑名称吗?它是否包含在查询的ColumnSet 中?实体对象的Attributes 属性包含什么?您是否尝试过调试代码?我还建议阅读 CRM SDK 的文档。

标签: c# plugins dynamics-crm


【解决方案1】:

使用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 与我的答案相比,这个答案提供了更广泛的问题背景,而不仅仅是解决方案。唯一补充:当字段的值为空或字段不存在时(例如名称中的拼写错误),字典不包含键。有两种可能的原因导致相同的结果,调试时可能会造成混淆。
  • 如果这是该类型的默认值,我将添加返回 null,因此对于像 decimal 这样的类型,您应该使用 decimal?
  • @sxntk 是的,相关阅读woodsworkblog.wordpress.com/2017/06/25/…
【解决方案2】:

代码应该是不言自明的:

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.");
}

【讨论】:

    【解决方案3】:
    Guid HeaderId; 
    
    if (entity.Attributes.Contains("new_LookupTransactionHeader"))
    {
     Guid HeaderId= ((EntityReference)entity["new_LookupTransactionHeader"]).Id; 
    }
    

    其余可自行添加,若包含返回false则不存在

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多