CRM 2011 - Add many to many relationship + checking if relationship exists between entities (N:N)

Hi all,

Using service context AddLink, you can create N:N relationship in CRM. However you still need to check if the relationship has already been created between the two entities, otherwise you would get 'Insert duplicate key' error.

Thanks to this blog I don't have to create helper functions to check the existing relationship. Rather than using AddLink method that is tied to a service context, I just use the normal Associate method of the IOrganisationService:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//Check if N:N relationship exists
public static bool IsNtoNRelationshipExists(IOrganizationService service,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 });
 
    return service.RetrieveMultiple(query).Entities.Count != 0;
}
 
//Add N:N Relationship
public static void AddLink(IOrganizationService service, Entity entity1, Entity entity2, Relationship rel)
{
    if (!IsNtoNRelationshipExists(service, entity1.LogicalName, entity2.LogicalName))
    {
        // Creating EntityReferenceCollection for the Contact
        EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
 
        // Add the related entity
        relatedEntities.Add(new EntityReference(entity2.LogicalName, entity2.Id));
        service.Associate(entity1.LogicalName, entity1.Id, rel, relatedEntities);
    }
}

HTH,
Andreas

Comments

Popular posts from this blog

SharePoint 2013 anonymous access add attachments to list item

CRM Plugin - Parent and Child Pipeline