Mar 31, 2015

Many–to-Many Associate, Disassociate and Retrieve

This is how you associate many-to-many relationships programmatically. One good thing about this approach is you can associate more than one record in one call. Disassociate too takes same parameters.

AssociateRequest request = new AssociateRequest();

EntityReference _ref1 = new EntityReference(<entity A - logical name>, <entity A - Guid>);
request.Target = _ref1;

EntityReferenceCollection _entRefColl = new EntityReferenceCollection();
_entRefColl.Add(new EntityReference(<entity B - logical name>, <entity B - Guid 1>));
_entRefColl.Add(new EntityReference(<entity B - logical name>, <entity B - Guid 2>));
request.RelatedEntities = _entRefColl;

request.Relationship = new Relationship("<relationship name>"); 
//relationship name ex: new_account_office

crmService.Execute(request);

Now one important fact;

Intermediate table of the many-to-many table is having the name of the relationship. For ex: new_account_office. This table got two Guids which are the primary key values of the two respective records to be associated which is obvious.

You are allowed to query this intermediate table as you wish. One thing to keep in mind is two Guids coming out of this table are purely Guids and NOT Entity References.

Probably, this is the only occasion you retrieve Guid from a table which are not the Primary key in CRM.  All other entity retrievals, if not a primary key we are retrieving Entity Reference type.  Clear?