C# – CRM 2011 Pre-Operation Update related entity lookup field

ccrmdynamics-crmdynamics-crm-2011microsoft-dynamics

I am attempting to update a related record in a CRM 2011 pre-operation update plug-in. A simple query retrieves a set of related entities based upon a couple of parameters and then each entity from the resultant query has it's lookup to the related entity set. However, when firing an exception is thrown suggesting an InvalidCastException. Having stepped through the code each of the values looks to be correct, Guids where expected etc. I have disabled other plug-ins which may involve the target and related entities, but still the problem persists. The relationship between the targetEntity and the relatedEntity is 1:N. I have confirmed that this issue is not because the attribute is expecting an EntityReference rather than a Guid while stepping through.

The code for the plug in is below, where I have substituted real entity/attribute names for more obvious proxies (it uses the developer toolkit Plugin class file):-

Entity targetEntity = (Entity)localContext.PluginExecutionContext.InputParameters["Target"];

        QueryExpression query = new QueryExpression
        {
            EntityName = "relatedEntity",
            Criteria =
            {
                Conditions =
                {
                    new ConditionExpression("testOptionSetAttribute", ConditionOperator.Equal, 100000004),
                    new ConditionExpression("parentEntityId", ConditionOperator.Null)
                }
            }
        };

        EntityCollection resultsCollection = localContext.OrganizationService.RetrieveMultiple(query);

        foreach (Entity result in resultsCollection.Entities)
        {
            result.Attributes["parentEntityId"] = targetEntity.Id;
            localContext.OrganizationService.Update(result);
        }

Any help would be appreciated.

Thanks.

Best Answer

I agree with Peter.

It must be an EntityReference, moreover it must be a new EntityReference.

Try this:

result.Attributes["parentEntityId"] = new EntityReference(targetEntity.EntityLogicalName, targetEntity.Id);
Related Topic