开发者

NHibernate One-To-One Relationships not saving correctly

I am having an issue with saving entities with o开发者_Go百科ne-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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜