This website is completely free and made possible by displaying online advertisements.
Please consider supporting us by disabling your ad blocker.

Querying Many-To-Many Relationship in MS CRM with C#

Microsoft CRM Jan 19, 2017

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);

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.