CRM 2011 KeyNotFoundException exception

 ̄綄美尐妖づ 提交于 2019-12-20 03:30:52

问题


I am new to CRM development. I have a Custom Entity "customer". This Entity has a Field called "defaultcustomer", which can be TRUE or FALSE. I am working on a Plug-In where i need to set the "defaultcustomer" to FALSE for all the "Customers". I am doing it as below:

FACTS:

I have registered the plugin for the entity "customer" itself. So when the Entity "customer" is updated, the plugin fires.

private void MakeAllNonDefault()
{

    try
    {
        QueryExpression query = new QueryExpression("customer");
        query.ColumnSet = new ColumnSet("defaultcustomer");

        EntityCollection retrieved = service.RetrieveMultiple(query);

        foreach (Entity myCustomer in retrieved.Entities)
        {

            myCustomer["defaultcustomer"] = false;
            service.Update(myCustomer);
        }

    }
    catch (Exception ex)
    {
        throw new InvalidPluginExecutionException("An error occurred in MakeAllNonDefault(): " + ex.ToString());
    }
}

ERROR: It throws error on this line:

myCustomer["defaultcustomer"] = false;

System.Collections.Generic.KeyNotFoundException: 
The given key was not present in the dictionary. 

回答1:


The error means that particular field is not present in the collection of properties. In CRM, only properties that have been set or updated are included.

Try something like:

foreach (Entity myCustomer in retrieved.Entities)
{
    if (myCustomer.Attributes.ContainsKey("defaultcustomer"))
    {
        myCustomer["defaultcustomer"] = false;
    }
    else
    {
        myCustomer.Attributes.Add("defaultcustomer", false);
    }
    service.Update(myCustomer);
}



回答2:


Have you double checked that the field really is called defaultcustomer?

If it's a custom entity then it's likely the field begins with a prefix, for instance new_defaultcustomer. Make sure you are using the name of the field, not the display name.




回答3:


The solution posted by @glosrob seems fine. Are you still getting "The given key was not present in the dictionary"?

Try to use ITracingService to get more information about the plugin execution flow.




回答4:


While Update all Crm fields are False accept that what you Update the field. For that you can use Pre/Post Images in Plugin. you will found that crm field key and update what you need.



来源:https://stackoverflow.com/questions/9901527/crm-2011-keynotfoundexception-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!