1
votes

I'm trying to create a plugin that changes all related contacts' address fields if the parent account's address field is changed in account form. I created a plugin to run in pre operation stage (update message against account entity) synchronously.

I used LINQ query to retrieve all related contacts and it works. Then I'm using foreach loop to loop trough all contacts and change them address fields. I'm using OrganizationServiceContext.AddObject(); function to add every contact to the tracking pipeline (or whatever it's called) and finally I'm using OrganizationServiceContext.SaveChanges(); to trying to save all contacts. But that's when I'm getting this error:

System.InvalidOperationException: The context is already tracking the 'contact' entity.

Here's my code

// Updating child contacts' fields
if (context.PreEntityImages.Contains("preAccount") && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) {
    if (((Entity)context.InputParameters["Target"]).Contains("address2_name")) {
        Entity account = (Entity)context.InputParameters["Target"];
        Entity preAccount = (Entity)context.PreEntityImages["preAccount"];
        if (account["address2_name"] != preAccount["address2_name"]) {
            EntityReference parentCustomer = new EntityReference(account.LogicalName, account.Id);
            Contact[] childContacts = orgService.ContactSet.Where(id => id.ParentCustomerId == parentCustomer).ToArray();
            foreach (Contact contact in childContacts) {
                contact.Address2_Name = (string)account["address2_name"];
                orgService.AddObject(contact);
            }
            orgService.SaveChanges();
        }
    }
}

What I'm doing wrong?

1

1 Answers

1
votes

You already attached the entities to the context when you retrieved the contacts with the query

Contact[] childContacts = orgService.ContactSet.Where(id => id.ParentCustomerId == parentCustomer).ToArray();

so you don't need to add again the entities to the context, instead you need to update them, by:

orgService.UpdateObject(contact); // this row instead of orgService.AddObject(contact);