CRM 2011 KeyNotFoundException exception

Yaqub Ahmad picture Yaqub Ahmad · Mar 28, 2012 · Viewed 7.9k times · Source

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. 

Answer

glosrob picture glosrob · Mar 28, 2012

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