Posts Tagged ‘N:N relationship’

Retrieve associated records (N:N related)

In CRM, If you create N:N relationship between 2 entities, it creates an intermediate entity (i.e., Relationship Entity) with 3 fields

  • Primary key field of “Relationship Entity”
  • Entity 1 Primary Key field
  • Entity 2 Primary Key field
N toN Relationship

N to N Relationship

In this sample, I have 2 custom entities “Bike” and “Bond” with N:N association. (i.e., A ‘Bike’ can have N no of ‘Bonds’ and a ‘Bond’ can be associate with N ‘Bikes’)

To get all the ‘Bonds’ of ‘Bike’ with name “Honda”, below is the query expression.

string entity1 = “raj_bike”;

string entity2 = “raj_bond”;

string relationshipEntityName = “raj_bike_bond”;

QueryExpression query = new QueryExpression(entity1);

query.ColumnSet = new ColumnSet(true);

LinkEntity linkEntity1 = new LinkEntity(entity1, relationshipEntityName, “raj_bikeid”, “{Entity 1 Primary key field (i.e.,raj_bikeid)}“, JoinOperator.Inner);

LinkEntity linkEntity2 = new LinkEntity(relationshipEntityName, entity2, “raj_bondid”, “{Entity 2 Primary key field (i.e.,raj_bondid)}“, JoinOperator.Inner);



// Add condition to match the Bike name with “Honda”

linkEntity2.LinkCriteria = new FilterExpression();

linkEntity2.LinkCriteria.AddCondition(new ConditionExpression(“raj_bikename”, ConditionOperator.Equal, “Honda”));

EntityCollection collRecords = service.RetrieveMultiple(query);

Note : To retrieve columns from Entity 2, set ‘Alias’ to ‘LinkEntity2’.