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.
Discover more from Nishant Rana's Weblog
Subscribe to get the latest posts sent to your email.
