Cry about...
Dynamics CRM 2011 How To

How to get all the entities in a one to many relationship (C#)

I had an entity which had a one to many relationship with a second entity, those second entities were listed on a sub-grid on a form and I needed a way to get those entities in a plugin.

The idea is straight forward, query the relationship between the entity and the entities in the sub-grid.

So, given the Entity, the logical name of the related entity and the logical name of the relationship the following function will return a EntityCollection of the related entities:

public EntityCollection ListRelatedEntities(Entity parent,
string relationshipLogicalName, string relatedEntity)
    // The relationship both (i.) defines the
    // relationship to the 'relatedEntity' and
    // (ii.) acts as a key into responses back.
    Relationship relationship = new Relationship()
        SchemaName = relationshipLogicalName
    RelationshipQueryCollection relatedEntityCollection = new RelationshipQueryCollection();
        new QueryExpression()
            EntityName = relatedEntity,
            ColumnSet = new ColumnSet(true)

    RetrieveRequest request = new RetrieveRequest()
        RelatedEntitiesQuery = relatedEntityCollection,
        ColumnSet = new ColumnSet(true),
        Target = new EntityReference
            Id = parent.Id,
            LogicalName = parent.LogicalName

    RetrieveResponse response = (RetrieveResponse)this._crmService.Execute(request);
    if (response == null) return null;
    if (response.Entity == null) return null;
    return response.Entity.RelatedEntities[relationship];

The above should work for both an N:N relationship as well as a 1:N relationship.

These notes have been tested with Microsoft Dynamics CRM 2011, and may apply to other versions as well.

About the author: is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.