I recently ran into a use case where I had to query a many-to-many realationship in an Microsoft CRM environment. Well, it’s always not that easy as it maybe seems on the first view. After a couple time researching and trying around I found a solution which I’ll share with you right here :-).

All you have to do is specify the entities and intersect entity name. In the result EntityCollection you’ll receive a list of the specified LinkEntity – in my case a list of contacts.

string entity1 = Contact.EntityLogicalName;
string entity2 = Campaign.EntityLogicalName;

QueryExpression query = new QueryExpression(entity1);
LinkEntity linkEntity1 = new LinkEntity(entity1, [Intersect Entity Name], "contactid", "contactid", JoinOperator.Inner);
LinkEntity linkEntity2 = new LinkEntity([Intersect Entity Name], entity2, "campaignid", "campaignid", JoinOperator.Inner);

linkEntity1.LinkEntities.Add(linkEntity2);
query.LinkEntities.Add(linkEntity1);

return this.organizationservice.RetrieveMultiple(query);