0

这可能很简单,但我想我错过了一些东西。我有一个自连接表Units,每个单元都有一个主单元:

在此处输入图像描述

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

在此处输入图像描述

该表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 之类的东西来应用等级等,因为我对其他更复杂的自我也有同样的问题具有更复杂查询的连接表。

4

1 回答 1

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
于 2011-06-18T04:21:32.890 回答