I have two classes with one-to-many relationship: Parent and Child.
Why the following code throws an exception?
Code:
// create a parent with one child
Parent parent = new Parent();
Child child = new Child();
parent.Children.Add( child );
child.Parent = parent;
session = factory.OpenSession();
tx = session.BeginTransaction();
parent = (Parent) session.SaveOrUpdateCopy( parent );
tx.Commit();
session.Close();
// remove child from parent
parent.Children.Remove( child );
session = factory.OpenSession();
tx = session.BeginTransaction();
Parent savedParent = (Parent) session.SaveOrUpdateCopy( parent );
tx.Commit();
session.Close();
session = factory.OpenSession();
tx = session.BeginTransaction();
// --> here is the problem <---
session.Delete( parent );
tx.Commit();
session.Close();
Exception:
Code:
NHibernate.HibernateException: SQL insert, update or delete failed (expected affected row count: 1, actual affected row count: 0). Possible causes: the row was modified or deleted by another user, or a trigger is reporting misleading row count.
hbm
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name="test.Parent, test" table="Parent">
<id name="Id" column="id" type="Int32" unsaved-value="-1">
<generator class="identity" />
</id>
<set name="Children" lazy="false" cascade="all-delete-orphan" inverse="true">
<key column="parent_id"/>
<one-to-many class="test.Child, test"/>
</set>
</class>
<class name="test.Child, test" table="Child">
<id name="Id" column="id" type="Int32" unsaved-value="-1">
<generator class="identity" />
</id>
<many-to-one name="Parent" class="test.Parent, test" column="parent_id" not-null="true"/>
</class>
</hibernate-mapping>