NHibernate Pitfalls: Cascades

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

For entities that have associations – one-to-one, one-to-many, many-to-one or many-to-many –, NHibernate needs to know what to do with their related entities, in three particular moments: when saving, updating or deleting. In particular, there are two possible behaviors: either ignore these related entities or cascade changes to them. NHibernate allows setting the cascade behavior for each association, and the default behavior is not to cascade (ignore).

The possible cascade options are:

None Ignore, this is the default
Save-Update If the entity is being saved or updated, also save any related entities that are either not saved or have been modified and associate these related entities to the root entity. Generally safe
Delete If the entity is being deleted, also delete the related entities. This is only useful for parent-child relations
Delete-Orphan Identical to Delete, with the addition that if once related entity is removed from the association – orphaned –, also delete it. Also only for parent-child
All Combination of Save-Update and Delete, usually that’s what we want (for parent-child relations, of course)
All-Delete-Orphan Same as All plus delete any related entities who lose their relationship

In summary, Save-Update is generally what you want in most cases. As for the Delete variations, they should only be used if the related entities depend on the root entity (parent-child), so that deleting the root entity and not their related entities would result in a constraint violation on the database.

                             

No Comments