Hi
My application has 3 items… portraits (ClassPortrait), painters(ClassPainter) and persons (ClassPerson). Each class has an associated table. This setup is used to model a many-to-many relationship. A portrait can have one or more painters.
When NHibernate creates the database, using the mapping files presented here, a constraint is set between painter and person. That is, there must be a person for every painter. (Seems ok to me).
When deleting a person, NHibernate tries to remove the person, without first removing the corresponding painter. This causing SQL Server to throw a constraint error.
Tracing the SQL statements I can see that NHibernate first UPDATES the person to be deleted, and after this NHibernate tries to DELETE the same entry. (Why first an UPDATE?)
I should have expected that NHibernate first deletes the painter entry, then deletes person. The constraints created indicates that NHiberate is avare about the relations in what I am thinking corrrect way (There should not be any painters without a link to a person).
So,,,can anyone help me? What’s wrong in my mapping files?
Code can be seen below.
Hibernate version:
1.2
Code between sessionFactory.openSession() and session.close():
ISession session = factory.OpenSession(interceptor);
ITransaction t = session.Transaction;
t.Begin()
session.Delete(person)
t.Commit() // Error is thrown here
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="ClassPerson,Entities" table="Person">
<id name="Id" column="id" unsaved-value="0">
<generator class="identity"></generator>
</id>
..
..
..
<bag name="Painter" inverse="false" table="Painter" cascade="all-delete-orphan" lazy="false">
<key column="PersonId"></key>
<one-to-many class="lgTronic.Spada.Business.Entities.ClassPainter,lgTronic.Spada.Business.Entities"></one-to-many>
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="ClassPainter,Entities" table="Painter">
<id name="Id" column="id" unsaved-value="0">
<generator class="identity"></generator>
</id>
..
..
..
<many-to-one name="ItemA" column="PortraitId" cascade="save-update" lazy="false" class="ClassPortrait,Entities"></many-to-one>
<many-to-one name="ItemB" column="PersonId" cascade="save-update" lazy="false" class="ClassPerson,Entities" >
</many-to-one>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="ClassPortrait,Entities" table="Portrait" lazy="false">
<id name="Id" column="id" unsaved-value="0">
<generator class="identity"></generator>
</id>
..
..
..
<bag name="Painter" inverse="false" table="Painter" cascade="all-delete-orphan" lazy="false" >
<key column="PortraitId"></key>
<one-to-many class="ClassPainter,Entities"/>
</bag>
</class>
</hibernate-mapping>