As per the OOB functionality all the child records of account like contacts, opportunities and activities etc., will be deleted on delete of account. But, in one of my project we got a requirement to remove the link with contacts instead of delete. I tried to customize the relationship but the CRM is not allowing us to do this.
Finally we ended up with writing the plugin to achieve this. We have to write this plugin on “Pre Validation” stage of “Delete” step on Account entity. The child records were not available in any other steps (Pre Operation for ex) as the CRM platform deletes all the child records first and then account. The following is the plugin code.
IPluginExecutionContext pluginContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService organizationService = serviceFactory.CreateOrganizationService(pluginContext.UserId); EntityReference targetEntity = (EntityReference)pluginContext.InputParameters["Target"]; QueryExpression getContacts = new QueryExpression("contact"); getContacts.Criteria.AddCondition(new ConditionExpression("parentcustomerid", ConditionOperator.Equal, targetEntity.Id)); EntityCollection allContacts = organizationService.RetrieveMultiple(getContacts); foreach(Entity contact in allContacts.Entities) { Entity contactToBeUpdated = new Entity("contact"); contactToBeUpdated.Id = contact.Id; contactToBeUpdated.Attributes["parentcustomerid"] = null; organizationService.Update(contactToBeUpdated); }
Happy coding !!!