问题
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:
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>
回答2:
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.
来源:https://stackoverflow.com/questions/2728160/hibernate-cascade-delete-on-a-bag