Use following function to associate records in n to n relationship
public void Associate()
{
string relationshipName = "bcrm_dot_document_dot_party_n_to_n";
string firstEntityName = "dot_document";
Guid firstEntityId = new Guid("69410885-8457-E811-80DC-005056BE7607");
string secondEntityName = "dot_party";
Guid secondEntityId = new Guid("A3BE0B8D-9C4A-E711-80D5-005056BE4FB8");
bool areEntitiesAlreadyAssociated = RelationshipExists(relationshipName, firstEntityId, firstEntityName, secondEntityId, secondEntityName);
if(areEntitiesAlreadyAssociated == false)
{
Relationship relationship = new Relationship(relationshipName);
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
EntityReference secondaryEntity = new EntityReference(secondEntityName, secondEntityId);
relatedEntities.Add(secondaryEntity);
crmService.Associate(firstEntityName, firstEntityId, relationship, relatedEntities);
}
}
Use following function to disassociate records in n to n relationship
public void Disassociate()
{
string relationshipName = "bcrm_dot_document_dot_party_n_to_n";
string firstEntityName = "dot_document";
Guid firstEntityId = new Guid("69410885-8457-E811-80DC-005056BE7607");
string secondEntityName = "dot_party";
Guid secondEntityId = new Guid("A3BE0B8D-9C4A-E711-80D5-005056BE4FB8");
Relationship relationship = new Relationship(relationshipName);
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
EntityReference secondaryEntity = new EntityReference(secondEntityName, secondEntityId);
relatedEntities.Add(secondaryEntity);
crmService.Disassociate(firstEntityName, firstEntityId, relationship, relatedEntities);
}
private bool RelationshipExists(string relationshipname, Guid entity1Id, string entity1Name,Guid entity2Id, string entity2Name)
{
string relationship1EtityName = string.Format("{0}id", entity1Name);
string relationship2EntityName = string.Format("{0}id", entity2Name);
//This check is added for self-referenced relationships
if (entity1Name.Equals(entity2Name, StringComparison.InvariantCultureIgnoreCase))
{
relationship1EtityName = string.Format("{0}idone", entity1Name);
relationship1EtityName = string.Format("{0}idtwo", entity1Name);
}
QueryExpression query = new QueryExpression(entity1Name)
{
ColumnSet = new ColumnSet(false)
};
LinkEntity link = query.AddLink(relationshipname,
string.Format("{0}id", entity1Name), relationship1EtityName);
link.LinkCriteria.AddCondition(relationship1EtityName,
ConditionOperator.Equal, new object[] { entity1Id });
link.LinkCriteria.AddCondition(relationship2EntityName,
ConditionOperator.Equal, new object[] { entity2Id });
EntityCollection entColl = crmService.RetrieveMultiple(query);
return entColl.Entities.Count != 0;
}
http://www.mscrmtutorial.com/2014/07/associate-and-disassociate-many-to-many.html

Like
Report
*This post is locked for comments