the given key was not present in the dictionary lookup CRM C# Plugin

你说的曾经没有我的故事 提交于 2019-12-12 04:57:48

问题


I have code to retrieve value from Lookup in CRM plugin using C#. It's simple, read guid from lookup then show it in exception.

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

throw new InvalidPluginExecutionException(HeaderId.ToString());

In this code I just want to get guid from lookup, but when I run the plugin I got error like this.

the given key was not present in the dictionary


回答1:


The code should be self-explenatory:

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:


Using entity["attribute"] indexer accesses the underlying Attribute property which is an AttributeCollection object, which behaves much like Dictionary<string, object>.

In this case the dictionary doesn't contain your key new_LookupTransactionHeader - this is probably because you have queried the data from CRM, and the value is null in CRM, in that case CRM omits the value from dictionary (even if you specifically requested it in a ColumnSet).

You can could check if the key exists in the dictionary before trying to access it, e.g. entity.Attributes.HasKey("new_LookupTransactionHeader").

You could also use entity.GetAttributeValue<EntityReference>("new_LookupTransactionHeader"), this will return null if the key doesnt exist (as opposed to throwing an exception.




回答3:


Guid HeaderId; 

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

The rest can be added on your own, if contains returns false, it does not exist



来源:https://stackoverflow.com/questions/46191782/the-given-key-was-not-present-in-the-dictionary-lookup-crm-c-sharp-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!