NHibernate one-to-one 关系时 正确的xml写法和curd写法

    技术2022-05-12  13

    parent.xml

     

    <class name="parent" table="parent">

      <id name="Id" type="Int32" unsaved-value="null">   <column name="id" length="4" sql-type="int" not-null="true" unique="true" />   <generator class="identity" />  </id>

      <one-to-one name="child" class="child" cascade="all" />

    </class>

     

     

    child.xml

     

    <class name="child" table="child">  <id name="Id" type="Int32" unsaved-value="null">   <column name="id" length="4" sql-type="int" not-null="true" unique="true" />      <generator class="foreign">        <param name="property">parent</param>      </generator>  </id>

      <one-to-one name="parent" class="parent" constrained="true" />

    </class>

     

     

    ------------------------------------------------------------------------------------------------------------------

    Save 存储的时候:

    parent p = new parent();

    child c = new child();

     

    c.parent = p;

    //p.child = c; //如果加上这个赋值,nhibernate会生成针对child表的update语句,因为是新生成记录,所以会出现“Unexpected row count: 0; expected: 1”错误提示。

     

    session.Save(c); //将在parent,child表中各自生成1条记录

    //session.Save(p); //将在parent表中生成一条记录,child表中没有记录

     

    -------------------------------------------------------------------------------------------------------------------

    Update 更新记录的时候

    parent p = session.Load(parentId);

    p.child.xxx = "xx";

     

    //p.child = new child(); //这种方式更新子类,将会出现“Unexpected row count: 0; expected: 1”错误提示。new 出来的child还处于transient临时状态,替换p.child则会出错。

     

    session.SaveOrUpdate(p); //这将同时更新parent和child表中的数据。

     

    --------------------------------------------------------------------------------------------------------------------

    Delete 删除记录的时候

    parent p = session.Load(parentId);

    session.Delete(p); //这样将同时删除parent和child表中的数据


    最新回复(0)