Programmatically Associate and Disassociate N:N relationship records in Microsoft Dynamics CRM 2011
Associate and Disassociate Contact record in Account entity. To perform this operation first we need to get the account contact relationship schema name. In my case it is “contact_customer_accounts”.
Below is the code to Associate N:N relationship record.
public static void AssociateContactsToAccount(EntityReference contact, EntityReference account, IOrganizationService service)
{
// Creating EntityReferenceCollection for the Contact
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
// Add the related entity contact
relatedEntities.Add(contact);
// Add the Account Contact relationship schema name
Relationship relationship = new Relationship("contact_customer_accounts");
// Associate the contact record to Account
service.Associate(account.LogicalName, account.Id, relationship, relatedEntities);
}
Disassociate N:N relationship records in CRM 2011
public static void DisassociateContactsToAccount(EntityReference contact, EntityReference account, IOrganizationService service)
{
// Creating EntityReferenceCollection for the Contact
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
// Add the related entity contact
relatedEntities.Add(contact);
// Add the Account Contact relationship schema name
Relationship relationship = new Relationship("contact_customer_accounts");
// Disassociate the contact record to Account
service.Disassociate(account.LogicalName, account.Id, relationship, relatedEntities);
}