views:

55

answers:

1

I am having an issue with saving entities with one-to-one relationships. I just want to save the parent entity and have the child be save aswell but I am having to save both separately.

This is an example of what I am having to do, otherwise the child is not saved.

 var session = SessionProvider.OpenSession.Session;
            using (var tx = session.BeginTransaction())
            {
                try
                {
                    session.SaveOrUpdate(parent);
                        if (parent.Child.IsPersisted)
                        {
                            session.Update(parent.Child);
                        }
                        else
                        {      
                            session.Save(parent.Child);
                        }
                    }
}


<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false" assembly="xxx">
  <class name="Parent" polymorphism="explicit" table="Parent">
    <id name="Id" column="JointID" type="int">
      <generator class="native" />
    </id>
    <one-to-one name="Child" class="Child" />
  </class>
</hibernate-mapping>


<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false"
                   assembly="xxx">
  <class name="Child" xmlns="urn:nhibernate-mapping-2.2" polymorphism="explicit" table="Child">
    <id name="Id" column="JointID" type="int" unsaved-value="0">
      <generator class="native" />
    </id>
    <many-to-one name="Parent" column="JointID" insert="false" update="false" />
  </class>
</hibernate-mapping>

Any ideas on how I can just make it save without having to do two save calls?

When I set the relationship to cascade as suggested below I get foreign key constraint errors. If I analyse the queries with NHProf, its trying to use the temporary id (-1) as the JointId in the insert statement rather than the newly created parent id. The JointId in the Parent table is an Identity key, perhaps that is an issue?

A: 

You'll need to enable cascading on your <one-to-one> mapping to have this work properly.

Something like:

<one-to-one name="Child" class="Child" cascade="save-update" /> 

You can read up on the various cascade settings here.

DanP
Added further detail to question regarding this. Thanks for pointing it out.
Dan
Are you setting the parent association of your child entity up propertly? You'll need to ensure that you're doing something like: parent.Child = child AND child.Parent = parent; could that be the issue?
DanP
Do I have to actually explicitly do that? I tried `parent.Child.Parent = parent` before saving and that has the same issue.
Dan
Have a look at: http://ayende.com/Blog/archive/2009/04/19/nhibernate-mapping-ltone-to-onegt.aspx there is some excellent guidance on one-to-one mappings there...
DanP