NHibernate映射自联接表?

时间:2011-06-18 03:00:31

标签: c# nhibernate nhibernate-mapping self-join

这可能很简单,但我想我错过了一些东西。我有一个自己加入的表Units,每个单位都有一个主要单位:

enter image description here

这样我就可以查询这样的内容:

enter image description here

units映射到以下类:

public class Units
{
    public virtual int Unit_Id { get; private set; }
    public virtual string Unit { get; set; }
    public virtual decimal Unit_Value { get; set; } 
    public virtual Units Main_Unit { get; set; }
}

使用.hbm映射文件如下:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NewA.Domain"     namespace="NewA.Domain">
   <class name="NewA.Domain.Entities.Units,NewA.Domain" table="Units">
    <id name="Unit_Id" column="Unit_Id" type="Int32" length="4" unsaved-value="0"> 
      <generator class="native">
      </generator>
    </id>
    <property name="Unit" column="Unit" type="string" length="50" not-null="true"/>
    <one-to-one name="Main_Unit" class="NewA.Domain.Entities.Units,NewA.Domain"/>
  </class>
</hibernate-mapping>

使用以下代码测试这些实体时:

Units unit = _UnitsRepository.GetById(2);
string parent_unitname = unit.Main_Unit.Unit;
Assert.AreEqual("pack",parent_unitname);

我得到了以下激励:

Expected values to be equal.

Expected Value : "pack"
Actual Value   : "kg"

问题是Main_Unit实体的Unit属性正在引用自身,所以我在这里缺少什么?以及如何编写类似递归SQL CTE的东西来应用等级等等on,因为我对其他更复杂的自连接表有更复杂的查询问题。

1 个答案:

答案 0 :(得分:3)

您需要多对一映射而不是一对一。 试试这个配置:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class xmlns="urn:nhibernate-mapping-2.2" name="NewA.Domain.Entities.Units.Units, NewA.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`Units`">
    <id name="Unit_Id" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Unit_Id" />
      <generator class="native" />
    </id>
    <property name="Unit" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Unit" />
    </property>
    <property name="Unit_Value" type="System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Unit_Value" />
    </property>
    <many-to-one class="NewA.Domain.Entities.Units.Units, NewA.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Main_Unit">
      <column name="Main_Unit_id" />
    </many-to-one>
  </class>
</hibernate-mapping>

我建议您尝试 Fluent NHibernate - 它可以为您动态生成映射。 这是我使用的配置:

var fluent = Fluently.Configure()
    .Mappings(c => c.AutoMappings.Add(AutoMap.AssemblyOf<Units>()
        .Override<Units>(u => u.Id(uu => uu.Unit_Id).GeneratedBy.Native())))
    .Database(() => SQLiteConfiguration.Standard.UsingFile("test.sqlite3"));

var configuration = fluent.BuildConfiguration();

// Generate database schema
new SchemaExport(configuration).Create(false, true);

var sessionFactory = configuration.BuildSessionFactory();
// Now just open session and do whatever you need