简体   繁体   中英

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

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

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, eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM