NHibernate Cascades: the different between all, all-delete-orphans and save-update
I have posted in the past about NHibernate's cascade being one of the places that require careful attention. But I run into an issue with it yesterday.
The issue was that we had a typical parent-children scenario, but the requirement changed and we had to support orphans. That is, children without a parent. This isn't that big of a deal, after all, and I told Imperial to just change the cascade from all-delete-orphan to all, and forgot about it.
I was called a few minutes afterward, and saw that the change didn't have the desired effect. The scenario that we were working on was deleting the parent, where the child needed to remain behind (will null foreign key, of course). Now, I was being stupid, and I started debugging into NHibernate to figure out what was the cause of this "bug". Ten minutes later (took a while to find where exactly this was happening), I had an "Oh, I am so dumb" moment.
So, to save myself from future embarrassment, let me try to articulate what it means:
Here is what each cascade option means:
- none - do not do any cascades, let the users handles them by themselves.
- save-update - when the object is saved/updated, check the associations and save/update any object that require it (including save/update the associations in many-to-many scenario).
- delete - when the object is deleted, delete all the objects in the association.
- delete-orphan - when the object is deleted, delete all the objects in the association. In addition to that, when an object is removed from the association and not associated with another object (orphaned), also delete it.
- all - when an object is save/update/delete, check the associations and save/update/delete all the objects found.
- all-delete-orphan - when an object is save/update/delete, check the associations and save/update/delete all the objects found. In additional to that, when an object is removed from the association and not associated with another object (orphaned), also delete it.
Fairly simple, isn't it? I have no idea why I managed to forget this. At any rate, my issue was that I set the cascade to all, and then deleted to root object, which naturally deleted all the child objects. Setting it to save-update was what I wanted to do, once I did that, everything went just fine.
Comments
Comment preview