Cascade on deletion using Many-To-Many unidirectional mapping

I use Fluent and NHibernate. I have two objects: A and B, which have a many-to-many relationship between them. I use many-to-many unidirectional mapping when A HasMany B's. There is no reference to A in B (unidirectional).

This creates a third table (named ABMapping) in the database, which has two columns related to primary keys A and B.

If I delete object A, the records from the ABMapping table associated with A will be deleted. That's cool.

But now I can not delete object B, because it has an FK constraint. How can I configure it so that when you delete B, all entries related to B in ABMapping are automatically deleted?

+3
source share
1 answer

If B does not refer to A, then he does not know about the mapping table, so he cannot cascade the deletion. As I can see, you have two options:

  • Cascade deletes in the database using cascading deletes on your FK or trigger.
  • Compare the relationship between B and A; you don’t need to expose it to the consumers of your class, collection A can be displayed as a private field using an access strategy. I always do this for collections (using .Access.CamelCaseField (Prefix.Underscore)) so that I don't expose IList.
+1
source

Source: https://habr.com/ru/post/1726889/


All Articles