Using Relationship and RelationshipQueryCollection class to retrieve n to n relationship details in CRM.

Suppose we need to query a n:n relationship and get details of both the entity records involved.

For this we can make use of Relationship and RelationshipQueryCollection class,

Suppose I have an entity named A  and it has n to n relationship with B  Entity.

This I how we can get the details all the A records associated with a particular entity B record.

i.e. Name of all the A records associated with a particular B entity record along with the  name of the B entity record.

</pre>
private void GetManytoManyRelationShipDetails(IOrganizationService _service, Guid entityBGuid)
 {
 // get offences records' name
 QueryExpression query = new QueryExpression("EntityA");
 ColumnSet cols = new ColumnSet();
 cols.AddColumn("EntityANameToBeRetreived");
 query.ColumnSet = cols;

// Relationship Name
 Relationship relationship = new Relationship("EntityA_EntityBRelationshipName");
 RelationshipQueryCollection relationshipColl = new RelationshipQueryCollection();
 relationshipColl.Add(relationship, query);

// get the legal issue record's name
 RetrieveRequest request = new RetrieveRequest();
 request.RelatedEntitiesQuery = relationshipColl;
 request.Target = new EntityReference("EntityB", entityBGuid);
 request.ColumnSet = new ColumnSet("EntityBNameToBeRetreived");
 RetrieveResponse response = (RetrieveResponse)_service.Execute(request);

string entityAName = string.Empty;

foreach (Entity entity in response.Entity.RelatedEntities[relationship].Entities)
 {
 entityAName += entity.Attributes["EntityAName"].ToString();
 }
 }

Hope it helps.

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s