Code Generating Code…programmatically retrieve N:N relationships

I recently needed to write a plugin that associated multiple different record types with a custom entity. The custom entity contained over 30 system many to many relationships with the other record types. 

There are couple of different approaches. One would’ve been to dynamically retrieve the relationship when the plugin ran, this means an extra call to the CRM service. The other option was to have a static dictionary mapping inside the plugin code. I chose the 2nd option because the relationships would not change and there is no need to make an additional call to the CRM service.

Now the time constraining task of copy pasting attributes and schema names from the customizations area. 30-45 seconds per copy paste would have taken around 15-20mins but there’s a better less error prone way.

Write a small console application to retrieve the N:N relationships for the entity and write out to te debug window and copy paste :)

Here’s the code, enjoy!

IOrganizationService sdk = null; // connect to crm here
 
RetrieveEntityRequest request = new RetrieveEntityRequest();
request.RetrieveAsIfPublished = true;
request.LogicalName = "...your entity name here...";
request.EntityFilters = EntityFilters.Relationships;
 
RetrieveEntityResponse response = (RetrieveEntityResponse)sdk.Execute(request);
EntityMetadata metadata = response.EntityMetadata;
 
if (metadata != null && metadata.ManyToManyRelationships != null)
{
    metadata.ManyToManyRelationships.ToList().ForEach(nn =>
    {
        System.Diagnostics.Debug.WriteLine("");
    });
}

2 Comments

Comments have been disabled for this content.