Dataverse raises Associate and Disassociate messages when records are linked or unlinked through relationship operations. Plug-ins can use these messages to enforce relationship rules, but must distinguish the relationship schema name and the related records involved.
When to use this approach
Understand Associate and Disassociate plug-in messages, relationship metadata and safe handling of many-to-many and one-to-many links.
Implementation steps
- Register the plug-in on the Associate or Disassociate message and select the appropriate stage and execution mode for the rule.
- Read the Relationship parameter as Relationship and the Target and RelatedEntities parameters from the execution context.
- Validate the relationship schema name before applying logic so the plug-in does not accidentally process unrelated relationships.
- Use the organization service only when additional reads or writes are necessary; avoid recursively changing the same relationship.
- Test both directions and both message types with the actual relationship configuration.
Example configuration or code
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.MessageName == "Associate" || context.MessageName == "Disassociate")
{
var relationship = (Relationship)context.InputParameters["Relationship"];
var target = (EntityReference)context.InputParameters["Target"];
var related = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];
if (relationship.SchemaName == "new_account_contact")
{
// Apply relationship-specific validation.
}
}
Common pitfalls
- Do not assume every relationship uses the same schema name or cardinality.
- Avoid unguarded updates that trigger the same plug-in logic recursively.
- Do not assume the related collection always contains exactly one record.
Validation checklist
Test associate and disassociate for the intended relationship, unrelated relationships, multiple related records and security failures.
Conclusion
Keep the design explicit, test the failure paths and document the operational steps so the solution remains maintainable after deployment.