Free NHibernate-One-to-Many Cascade Delete

I've seen this problem a lot, but none of the solutions worked for me.

I have a one-to-many relationship in C # mapped to MS SQL with white NHibernate. When I try to remove the child NHibernate tries to do so by setting the foreign key to NULL

, which of course throws an error.

Solutions for similar issues was to add Inverse

a HasMany

parent to the display . However, now there is this problem:

var parent = //something


This will delete the entire parent! Why?


source to share

1 answer

The use of "Reverse" in matching overrides the concept of who "owns" the parent-child relationship. By specifying "Reverse", NH basically acts as if the child side of the relationship is deciding if it belongs to the Parent, rather than the Parent deciding if it has a Child. College students are a good example for the real world. The student may no longer participate in college and may still exist and be significant as an entity. It is also the Student, not the College, which is the primary decider of whether to form or break this attitude towards College (in real life, yes, there are situations where the college says that the student is no longer welcome, but the college does not just tell the student that " you drop out, "this is a student talking to college).

Not to mention, by specifying the relationship between parent and children as the opposite, NH treats "one" side of the relationship (Parent) as a side that cannot exist outside the context of the relationship. So, when you clear all the children, the parent who now has no children is "orphaned" and NH removes him.

This doesn't sound like what you want; so I would remove the inverse mapping from this relationship, allowing the Parent to "own" the relationship with their children. Remove all children and they become orphans and removed, but the Parent is still around. Now you have the problem that children cannot be orphaned because a foreign key cannot be invalid; they must belong to something. NH requires the FKs of the child records to be nullable if you are going to use cascading orphan deletion rules. This is because removing orphans is a two-pass operation that requires the record to be lost first by setting its FK field to zero. NH will then run a second statement to remove any record with NULL FKs from the table. Thus, even with a zero field FK,using NH with the required cascading rules, you won't have any zero FK entries for more than a transition period.

If this is not acceptable, you will have to remove the orphan removal from the cascading rules and manually remove each entry and also remove it from the session.

foreach(var child in parent.Children)





All Articles