简体   繁体   中英

Hibernate cascade delete on a bag

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

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM