In this walkthrough we will learn how to take care of the "The given key was not present in the dictionary" - "KeyNotFoundException" error in a Dynamics CRM 2013 (2011) Plug-in or custom Workflow.
- A disadvantage of using late-binding when coding a CRM 2013 Plugin is, you shoud be very careful with the attributes names, since there is no compile time checking.
- Specially when you have added a new field to an entity, and you get the "The given key was not present in the dictionary" Exception, you'll be prone to think something is not good with the new field definitions, or worse , the Organization Web Service is not recognizing the new field, or even worse, the Web Service needs to be reset to render the field, or may be you'd be desperately thinking to restart the CRM server to refresh the Web Service.
- That's because the error message by CRM may be misleading : you may be expecting that, in case your new field contains a null value, CRM Retrieve() or RetrieveMultiple() or Execute() will locate the field attribute, and fetch a NULL value for it. But CRM wouldn't : it WILL NOT INCLUDE THE KEY IN THE ATTRIBUTE'S DICTIONARY UNLESS IT CONTAINS A VALUE : if your field is not a REQUIRED field, you must code a checking for the presence or absence of the field.
- For instance, let's say you've added a new field named "new_test", and inside your Plug In you fetch it as follows:
- If the present entity has a NULL value in it , you'll be faced to the "The given Key..." exception:
- First think you'll want to check, is whether you requested for the field in the ColumnsSet:
- But that's not the problem. You did indeed. However, the "new_test" field attribute IS NOT THERE:
- That's because CRM WILL NOT INCLUDE THE KEY IN THE ATTRIBUTE'S DICTIONARY UNLESS IT CONTAINS A VALUE (meaning it was SET or UPDATED).
- You MUST perform a check for the field existence, but not a NULL check as this:
- You should instead use the ContainsKey(string) method from the Collection, for EVERY NO REQUIRED FIELD on the Entity:
Hoping it helped you.
That's all...Enjoy Dynamics CRMכתב: כרמל שוורצמן