Cascading delete for optional inverse joins

364 Views Asked by At

There is a following simplified mapping for one of our entity classes:

 <class name="Parent" table="tParent">
    <id name="Id">
      <column name="ParentId" sql-type="bigint"/>
      <generator class="native"/>
    </id>
    <join table="tOneToOneComponent" optional="true" inverse="true">
      <key column="ParentId" on-delete="cascade"/>
      <property name="Someprop"/>
    </join>
  </class>

Basically, it's one-to-one with the foreign key from the other side of the relation (that's why we set "inverse"). Also, Parent might have no any records in the tOneToOneComponent (so comes the optional="true").

I know, such joins are not recommended, but we have a bit old and large system and we have no time to redesign it.

We would like NHibernate to delete the related tOneToOneComponent when the Parent gets deleted.

Of course, we could cascade the delete operation on the SQL server, but then we need to clear NHibernate cache to ensure that the tOneToOneComponent does not stay somewhere in the cache.

So we added the on-delete="cascade" to the but now when we delete a Parent, SQL says:

The DELETE statement conflicted with the REFERENCE constraint

It seems, NHibernate is trying to delete the records in the wrong order.

How to tell NHibernate to delete tOneToOneComponent first (if it exists) and only then delete the parent?

1

There are 1 best solutions below

0
On

what you want is the default behavior which is overidden by Inverse() which tells it that it must not delete the other part at all since it owns himself. Either get rid of Inverse() or handle delete in another way.