Retrieve associated records (N:N related) in CRM

Hi,

In CRM, many times we create N:N relationship between 2 entities. When ever we do this, CRM internally creates an intermediate entity with 3 fields.

1) Primary key field of newly created entity.
2) First entity Primary Key field
3) Second entity Primary Key field

In my example, I have two entities called Books and Authors. One book can be written by multiple authors and one author can write multiple books.

Here is the code to retrieve Books written by Author ‘Gopinath’

string strFirstEntity = “books”;

string strSecondEntity = “authors”;
string strRelationshipEntityName = “books_authors”;
QueryExpression query = new QueryExpression(strFirstEntity);
query.ColumnSet = new ColumnSet(true);
LinkEntity linkEntity1 = newLinkEntity(strFirstEntity, strRelationshipEntityName, “books”, “booksid”, JoinOperator.Inner);
LinkEntity linkEntity2 = newLinkEntity(strRelationshipEntityName, strSecondEntity, “authors”, “authorsid”, JoinOperator.Inner);
linkEntity1.LinkEntities.Add(linkEntity2);
query.LinkEntities.Add(linkEntity1);
// Add condition to match the Author name with “Gopinath”
linkEntity2.LinkCriteria = new FilterExpression();
linkEntity2.LinkCriteria.AddCondition(new ConditionExpression(“name”, ConditionOperator.Equal, “Gopinath”));
EntityCollection collRecords = iService.RetrieveMultiple(query);

Hope this helps.


Happy CRM’ing

Gopinath

One thought on “Retrieve associated records (N:N related) in CRM

  1. Herry Johnson July 20, 2016 / 7:29 am

    We are expert and professional in ms crm series. Here are option for the all these articles Microsoft Dynamics CRM : Ms crm 2011 , 2013 and 2015 step by step tutorial of ms crm error in mscrm plugin workflow ms crm javascript Code .

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s