Handling N:N relationships in Dynamics CRM plugins

By | April 11, 2016

Here is a quick and dirty example of how a plugin could be created to handle N:N associations. A plugin like this would need to be registered for the “Associate” message of “any” entity:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;

public void Execute(IServiceProvider serviceProvider)
{
  IPluginExecutionContext context = (IPluginExecutionContext)
      serviceProvider.GetService(typeof(IPluginExecutionContext));
 if (context.InputParameters.Contains(“Target”) &&
     context.InputParameters[“Target”] is EntityReference &&
     ((EntityReference)context.InputParameters[“Target”]).LogicalName == YOUR_ENTITY_NAME)
 {
   if (context.InputParameters.Contains(“Relationship”))
   {
                  
      Relationship relationship = (Relationship)context.InputParameters[“Relationship”];
      if (relationship.SchemaName != YOUR_RELATIONSHIP_SCHEMA_NAME) { return; }

      EntityReferenceCollection re = (EntityReferenceCollection)context.InputParameters[“RelatedEntities”];

      //PROCESS THE COLLECTION

   }
 }

}

Leave a Reply

Your email address will not be published. Required fields are marked *