Check One Entity’s Relationships in Dynamics CRM 2011

Zhen Yuwang, 04 August 2012

Thanks to Microsoft Dynamics CRM 2011 Solutions; we can separate components and functions into different Solutions. Then they could be imported depending on the requirement. So, different Solutions could have different Entities and Relationships.

Later, when developing plugins which work across multiple solutions we may want to know, does this Entity have a relationship with another Solution’s Entity.  We can implement this check by following steps.

Assume you have a Solution with an Entity “Membership”.

 Check One Entity Relationships in Dynamic CRM 2011

There is a Contact look up field on “Membership” form. Hence, there is a 1:N relationship in Contact Entity.

 Check One Entity Relationships in Dynamic CRM 2011

 
Check One Entity Relationships in Dynamic CRM 2011

To find this relationship:

1. Create a RetrieveEntity Request. Set its LogicalName to “contact”.  As we only want the entity’s relationships information, we should set EntityFilters to “Relationships”.

RetrieveEntityRequest retrieveContactRequest = new RetrieveEntityRequest{
EntityFilters = EntityFilters.Relationships,
       LogicalName = "contact"
}; 

2. Execute the Request and obtain the response.

RetrieveEntityResponse retrieveContactResponse = (RetrieveEntityResponse)_sdk.Execute(retrieveContactRequest);

3.  For each 1-to-Many relationship, if it is a Custom relationship, print out the Reference Entity and Schema Name. If its Reference Entity equals “mag_membership”, then we know the relationship, which we are looking for, exists in current Dynamic CRM 2011 instance. Set “hasMembership” to true.

bool hasMembership = false;

retrieveContactResponse.EntityMetadata.OneToManyRelationships.ToList().ForEach(a =>
{
if (a.IsCustomRelationship.Value)
{
Console.WriteLine("Custom 1:N Relationship:");
       Console.WriteLine("ReferencingEntity={0}", a.ReferencingEntity);
Console.WriteLine("SchemaName={0}", a.SchemaName);
if (a.ReferencingEntity.Equals("mag_membership"))
{
hasMembership = true;
    }
}
});
Console.WriteLine("hasMembership: {0}", hasMembership);

4. Now, have a look at the result in console. 

 Check One Entity Relationships in Dynamic CRM 2011