Retrieve data from N-N relationship in CRM

Sharing a sample code to retrieve data from N-N relationship in CRM. We have a trainer profile which have N-N relationship with Centre that means one trainer can visit to multiple centre and one centre can be assigned to multiple trainers. Here we are trying to retrieve list of centres associated with particular trainer.

List<Centre> centreList = new List<Centre>();
QueryExpression query = new QueryExpression(“mc_centre”);
query.ColumnSet = new ColumnSet(new string[] { “mc_centreid”, “mc_name” });

LinkEntity linkEntity1 = new LinkEntity(“mc_centre”, “mc_mc_trainer_mc_centre”, “mc_centreid”, “mc_centreid”, JoinOperator.Inner);
LinkEntity linkEntity2 = new LinkEntity(“mc_mc_trainer_mc_centre”, “mc_trainer”, “mc_trainerid”, “mc_trainerid”, JoinOperator.Inner);


linkEntity2.LinkCriteria = new FilterExpression();
linkEntity2.LinkCriteria.AddCondition(new ConditionExpression(“mc_trainerid”, ConditionOperator.Equal, new Guid(trainerId)));

EntityCollection centreCollection = service.RetrieveMultiple(query);
if (centreCollection.Entities.Count > 0)
foreach (var centre in centreCollection.Entities)
Centre cr = new Centre();
cr.centreId = centre.Attributes[“mc_centreid”].ToString();
cr.centreName = centre.Attributes[“mc_name”].ToString();

return centreList

%d bloggers like this: