System.Collections.Generic.KeyNotFoundException Dynamics CRM C# lookup field error

918 views Asked by At

I am trying to create a new record in Dynamics CRM using C#.

Below is the code that I am using:

 Entity Record = new Entity("new_edRecord");
 Record["new_year"] = "2100";
 Record["new_school"] = new EntityReference("new_school",new Guid("8ba53949-3947-e445-876c-001dd8b71c19"));
 Record["new_gradelevel"] = "100000018";
 organizationProxy.Create(Record);

When I execute this, I get the below error:

Unexpected exception from plug-in (Execute): Department.EdRecord.RecordCreate: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.

I double checked to see if a school exist with the GUID by visiting the below url:

https://crm.site.com/orgname/api/data/v8.0/new_schools(8ba53949-3947-e445-876c-001dd8b71c19)

and this brought a result. Not sure what I am missing here.

3

There are 3 answers

2
Aron On

It is a common convention to name CRM lookup fields as the entity name with id appended.

Is it possible that Record["new_school"] should be Record["new_schoolid"]?

OR:

Perhaps the value 100000018 does not exist in the Record["new_gradelevel"] optionset. Maybe comment out that line and see what happens.

0
Aakarsh Dhawan On

If new_gradelevel is an Optionset type of field, following should be the code-:

Record["new_gradelevel"] = new OptionSetValue(100000018);

Also, can you confirm the data type of new_year is String.

Hope it helps.

0
Arun Vinoth-Precog Tech - MVP On

Like other answers suggested, verify all the field names/schema names for its correctness.

You can do trial & error by commenting out the fields one by one and execute this code to find out the buggy line.

Finally, (this will be my first troubleshooting step) cross check if you have any other plugins on post create of new_edrecord entity or associate of new_school entity. That synchronous plugin may throw this KeyNotFoundExceptionerror but bubble here.