In CRM, the Associate or Disassociate event happens:

If you have a N:N relationship between two entities and when you try to associate or disassociate records either from Associated view or Sub grid.

In Plugins, the Associate & Disassociate messages behave little different than other messages.

When you register a plugin on Associate message, you have to leave “Primary and Secondary” entities as ‘none’.

Since we don’t provide entity names, the registered Plug-in step triggers on all “Associate” operations, so we have to check few conditions to let the “Association” trigger happen only between intended entities.
You can use the below code template for Associate or Disassociate plugins

EntityReference targetEntity = null;

string relationshipName = string.Empty;

EntityReferenceCollection relatedEntities = null;

EntityReference relatedEntity = null;

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

// Get the “Relationship” Key from context

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

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

}

// Check the “Relationship Name” with your intended one

if (relationshipName != “{YOUR RELATION NAME}”) {

return;

}

// Get Entity 1 reference from “Target” Key from context

if (context.InputParameters.Contains(“Target”) && context.InputParameters[“Target”] is EntityReference) {

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

}

// Get Entity 2 reference from ” RelatedEntities” Key from context

if (context.InputParameters.Contains(“RelatedEntities”) && context.InputParameters[“RelatedEntities”] is EntityReferenceCollection) {

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

relatedEntity = relatedEntities[0];

}

}

Advertisements