aminvincent
aminvincent

Reputation: 603

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

Upvotes: 0

Views: 1563

Answers (3)

James Wood
James Wood

Reputation: 17562

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.

Upvotes: 3

AllanC
AllanC

Reputation: 813

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

Upvotes: 1

jcjr
jcjr

Reputation: 1503

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

Upvotes: 1

Related Questions