Nhibernate映射List <class>其中Class有自己的表</class>

时间:2013-04-17 15:21:20

标签: c# .net nhibernate nhibernate-mapping

我正在尝试为类创建映射:

public class Employer
    {
        public virtual int Id { get; protected set; }
        public virtual string Name { get; set; }
        public virtual IList<Field> Fields { get; set; }
        public virtual string Location { get; set; }
        public virtual string Phone { get; set; }
    }

public class Field
    {
        public virtual int Id { get; protected set; }
        public virtual string Description { get; set; } 
    }

我的映射看起来像:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="lab" assembly="lab">

  <class name="Employer" table="Employer">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="Name" />

    <list name="Fields" cascade="all-delete-orphan">
      <key column="EmployerId" />
      <index column="FieldIndex" />
      <one-to-many class="Field"/>
    </list>

    <property name="Location" />
    <property name="Phone" />
  </class>

</hibernate-mapping>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="lab" assembly="lab">

  <class name="Field" table="Field">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="Description" />
  </class>

</hibernate-mapping>

代码如下:

var session = configuration.BuildSessionFactory().OpenSession();
var transaction = session.BeginTransaction();
var emp = new Employer();
emp.Name = "Mera";
emp.Fields = new List<Field> ();
emp.Fields.Add(new Field() { Description = "C#" });
emp.Fields.Add(new Field() { Description = "C++" });
emp.Location = "Street";
emp.Phone = "02";
session.Save(emp);
transaction.Commit();

var transaction2 = session.BeginTransaction();
var emp2 = new Employer();
emp2.Name = "Mera2";
emp2.Fields = session.CreateQuery("from Field").List<Field>();
emp2.Location = "Street";
emp2.Phone = "02";
session.Save(emp2);
transaction2.Commit();

此代码只是将Field表中的旧条目替换为第二个雇主的新条目。因此,Field表仍有2条记录,Employer表有2条记录。

你可以理解我需要,如果2个字段相同(相同的描述),2个雇主都应该有相同的对象引用。

1 个答案:

答案 0 :(得分:3)

正如JamesB在评论中所说,这看起来像是多对多的关系。多对多关系需要一个中间表,否则你将获得你所看到的行为。

要获得所需的行为,您需要创建一个名为EmployerFields的新表。此表需要有两个外键字段,一个用于Employer,另一个用于Fields,还有一个字段用于索引FieldIndex。 FK可以分别称为EmployerIdFieldId

然后需要更改列表映射,如下所示。

<list name="Fields" cascade="all-delete-orphan" table="EmployerFields">
  <key column="EmployerId" />
  <index column="FieldIndex" />
  <many-to-many class="Field" column="FieldId" />
</list>