tags:

views:

125

answers:

2

Howdy,

Having built most of my DAL using NHibernate, I've now discovered that the SQL Server's Cascade On Delete rules also need to be taken into account in my HBM files too. I've been using bags for all my collections, but there doesn't seem to be a way to add a cascade="delete" attribute to a bag. I can change all my bags to sets, but that appears to mean I have changing all my IList<>s on my models to PersistentGenericSet<>s, which I don't really fancy doing.

Any advice?

Anthony

+1  A: 

There are two separate-but-related concepts: NHibernate's cascading rules, and DB cascading.

The latter is actually configured on the key element so, if the FK has ON DELETE CASCADE, this is what the bag should look like:

<bag name="Children" ...>
  <key column="ParentId" on-delete="cascade"/>
  <one-to-many class="Child"/>
</bag>
Diego Mijelshon
This is correct but I want to point out that the on-delete setting is used when creating the database script from NHibernate. It will create a foreign key with on delete cascade. It will not cascade deletes of your objects.
Jamie Ide
Actually, it modifies the behavior of NHibernate, because it's now aware of the existence of the *on delete cascade* behavior so, if you have `cascade="all"`, it will rely on the DB to do it instead of deleting child objects one by one.
Diego Mijelshon
Just tried that and I get the following error:Only inverse one-to-many associations may use on-delete="cascade"
littlecharva
Yes, you need to make the association bidirectional (Children must have a reference to Parent) and put `inverse="true"` in the bag.
Diego Mijelshon
Thanks, that worked like a treat.
littlecharva
+1  A: 

You can add a cascade attribute to a bag mapping. The documentation lists several options for the attribute cascade="all|none|save-update|delete|all-delete-orphan". The most commonly used option for a one-to-many relationship is all-delete-orphan. Setting cascade to this value will cause all database operations to be cascaded to the collection and child objects will be deleted if they are removed from the collection (orphaned).

Database cascades are similar but do not offer the ability to automatically delete an orphaned child record. Setting the cascade option in NHibernate and in the database is somewhat redundant but may be useful if you have other systems accessing the database directly.

Jamie Ide