简体   繁体   中英

CRM Plugin Error The given key was not present in the dictionary

I developed a CRM plugin that gets triggered when creating a Case entity. The Case has a N:1 relationship with another custom entity. Short story, when a field "new_CaseAssign" from the custom entity is set to 1, then the plugin will generate a Task assigned to Case Owner.

However the problem is that the field "new_CaseAssign" is newly added so most of the custom entity records don't have this field set yet, which causes the plugins to error out with "The given key was not present in the dictionary". If the custom field has value, then it's no problem.

What would be the best way to handle this situation? I tried customEntity.Attributes.Contains("new_CaseAssign") like below codes but no success:

var new_CaseAssign = customEntity.Attributes["new_CaseAssign"];

if ((customEntity.Attributes.Contains("new_CaseAssign")) && (bool)new_CaseAssign)
        {
            activityEntity.Attributes.Add("ownerid", incident.Attributes["ownerid"]);
        }
        else 
        { //something else
        }

Any suggestions is appreciated. Thanks much.

The line:

var new_CaseAssign = customEntity.Attributes["new_CaseAssign"];

is probably causing the exception. You could rewrite the code as:

bool new_CaseAssign = false;
if (customEntity.Attributes.Contains("new_CaseAssign"))
    new_CaseAssign = (bool) customEntity.Attributes["new_CaseAssign"];

if (new_CaseAssign) {
    activityEntity.Attributes.Add("ownerid", incident.Attributes["ownerid"]);
}
else { //something else
}

So first check contains before trying to access the key.

Loathing's answer is partially correct, in fact you are accessing the attribute before the check if is present or not. Normally I also check if the attribute it's not null before the cast.

The second error is with the field name, you are using late bound style, this means you need to use the logical name instead of the schema name, so the field name is new_caseassign (all lower case) instead of new_CaseAssign .

if ((customEntity.Attributes.Contains("new_caseassign")) && customEntity.Attributes["new_caseassign"] != null)
{
    if ((bool)customEntity.Attributes["new_caseassign"])
    {
        activityEntity.Attributes.Add("ownerid", incident.Attributes["ownerid"]);
    }
}
else 
{ //something else
}

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