NHibernate Pitfalls: Cascades

Posted by Ricardo Peres on ASP.net Weblogs See other posts from ASP.net Weblogs or by Ricardo Peres
Published on Sat, 07 Jul 2012 09:05:00 GMT Indexed on 2012/07/07 15:16 UTC
Read the original article Hit count: 248

Filed under:
|
|

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.

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about nhibernate