March 16, 2014

Dynamics CRM - Delete does not trigger Disassociate; Need pre validation plugin to retrieve existing N-N relationships.

Whoever worked with multi-multi (N-N) standard relationships in CRM knows that you can trigger plugins on the Associate and Disassociate messages. They fire when you add / remove a N-N relationship between two records.

You would expect that when you delete one of the records from the N-N relationship this would also trigger a Disassociate message, after all the association is also removed. It does not.
Because of that if you want to program something that triggers whenever a N-N relationship between two records is removed is is not enough to trigger on the Disassociate message. You also need to trigger your logic on the Delete (and probably SetStateDynamicEntity, for inactivation) messages.

So far so good, but how to retrieve all the N-N related records from the other entity? This can be done by querying the "hidden" N-N cross entity, which can be found under "Relationship Entity Name" when you open the properties of any N-N relationship.

Using LINQ the query would look something like this:

// data - instance of the service context
from nn in data.nn_relationship_entity
where nn.relationship1id = FILTER_ID
select nn.relationship2.Value

An important thing to note is that if you run this in the Pre-Operation stage of the Delete message it will return 0 rows! The correct place (one of the very few examples) is the Pre-Validation phase. If run there it will correctly return the ID's of all related records, on which you can then run you disassociation logic.

Hope this helps someone...