Dynamics CRM: Associate & Disassociate messages in the plugins

By | June 10, 2016

I have seen  a few examples of how to handle associate/disassociate messages in the plugins, and I have done it myself multiple times; however, some of those examples don’t work as is, and, more often than not, I have to spend more time than I’d like to on this kind of plugins.

The code below is fresh from the Visual Studio, having been tested in CRM 2013 just now (yes, it is not the latest version.. keep that in mind if something there does not work when you copy-paste it to your plugin and try to use for CRM 2015/2016).

Once the code has been compiled, use PluginRegistrationTool to register the plugin and to create a step for “Associate” and/or for “Disassociate” messages. You won’t be able to define an entity for those messages, so it’s important to verify the name of the relationships in the plugin code before doing anything else.

public class AssociateDisassociate : IPlugin
{

public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

if (context.MessageName == “Associate” || context.MessageName == “Disassociate”)
{

if (context.InputParameters.Contains(“Relationship”))
{

Relationship rel = (Relationship)context.InputParameters[“Relationship”];

if (rel.SchemaName != “{RELATIONSHIP NAME}”)
{
return;
}

if (context.InputParameters.Contains(“Target”) && context.InputParameters[“Target”] is EntityReference)
{
targetEntity = (EntityReference)context.InputParameters[“Target”];
if (context.InputParameters.Contains(“RelatedEntities”) && context.InputParameters[“RelatedEntities”] is EntityReferenceCollection)
{

relatedEntities = context.InputParameters[“RelatedEntities”] as EntityReferenceCollection;
relatedEntity = relatedEntities[0];
}

//check both relatedEntity and targetEntity – they might switch sides depending on what message is being handled and from where it came from

}
}
}

}
}

3 thoughts on “Dynamics CRM: Associate & Disassociate messages in the plugins

  1. Ashwin

    targetEntity = (EntityReference)context.InputParameters[“Target”];

    In the above code, is that possible to retrieve the targetEntity Id. I tried your code and getting the Entity Logical Name but i can get the Id of the record.

    Reply
  2. Ashwin

    targetEntity = (EntityReference)context.InputParameters[“Target”];

    I cant able to reterive the targetEntity Id, though i get the logical name of the entity.

    Reply
    1. Alex Shlega Post author

      targetEntity.Id should give you the id. Do you mean you are getting an empty guid for some reason?

      Reply

Leave a Reply

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