问题
I am using Fluent and NHibernate. I have two objects say A & B which has a many-to-many relationship between them. I am using a unidirectional many-to-many mapping when A HasMany B's. There is no reference in B about A (Unidirectional).
This creates a third table (named ABMapping) in the Database which has the two columns relating to primary keys of A & B.
If I delete the object A, the entries from the ABMapping table related to A are deleted. That's cool.
But, now I am not able to delete an object B, as it has a FK constraint. How can I set it up so that on deleting B, all entries related to B in ABMapping are deleted automatically?
回答1:
If B doesn't reference A then it doesn't know about the mapping table so it can't cascade the delete. As I see it you have two options:
- Cascade the delete in the database using cascading deletes on your FK or a trigger.
- Map the relationship from B to A; you don't have to expose it to consumers of your class, the A collection could be mapped 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.
来源:https://stackoverflow.com/questions/1980177/cascade-on-delete-using-unidirectional-many-to-many-mapping