NHibernate - 一对一映射

时间:2011-01-23 18:03:52

标签: nhibernate nhibernate-mapping one-to-one

我在Person类和Employee之间有一对一的关系。我希望INSERT从Person级联到Employee。但是,这不会发生。我在一对一关系元素上尝试过cascade ='all'和cascade ='save-update',但它没有用。我还上传了我的完整源代码:http://bit.ly/gnkxBr(3.52 MB)

我的对象的结构如下:

public class Person
{
    public virtual Employee Employee { get; set; }
    public virtual int Age { get; set; }
    public virtual string Forename { get; set; }
    public virtual string Surname { get; set; }
    public virtual int PersonID { get; set; }
}

public class Employee
{
    public virtual int PersonID { get; set; }
    public virtual string PayRollNo { get; set; }
    public virtual int Holidays { get; set; }
    public virtual Person Person { get; set; }
}

映射文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Person, Employee.DAL" table="`Person`"  >
    <id name="PersonID" column="`PersonId`" type="int">
      <generator class="native" />
    </id>
    <property type="string" name="Forename" column="`Forename`" />
    <property type="string" name="Surname" column="`Surname`" />
    <property type="int" name="Age" column="`Age`" />
    <one-to-one name="Employee" class="Employee" cascade="all" />
  </class>
</hibernate-mapping>


<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Employee, Employee.DAL" table="`Employee`" >
    <id name="PersonID" column="`PersonId`">
      <generator class="foreign">
        <param name="property" >Person</param>
      </generator>
    </id>
    <property type="string" length="30" name="PayRollNo" column="`PayRollNo`" />
    <property type="int" name="Holidays" column="`Holidays`" />
    <one-to-one name="Person"  class="Person" constrained="true" />
  </class>
</hibernate-mapping>

1 个答案:

答案 0 :(得分:0)

将session.Save()方法放在事务中。或者在调用save方法后使用session.Flush()方法。