Programmatically Associate and Disassociate N:N relationship records in Microsoft Dynamics CRM 2011

Posted: October 28, 2012 in Code Snippets, CRM 2011

Associate N:N relationship records in CRM 2011

In my example, im gonna associate and disassociate Contact record in Account entity. To perform this operation first we need to get the accout 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);
            
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s