Nhibernate子类映射问题

时间:2009-11-07 21:33:29

标签: c# asp.net nhibernate orm

我正在使用nhibernate子类映射来处理系统对象的描述。基本上,想法是通过具有特定于对象的子类来具有描述类并进行多态关联。我的代码正确地将描述数据插入数据库;这意味着在插入数据时会正确创建ownerid和ownertype列。

但是当我使用nhibernate.load()加载Foo对象时,nhibernate没有使用OwnerType列来查询Foo的描述 - 它只使用ownerId列查询描述表,这会产生冲突,因为可能有其他行具有相同id但与不同ownertype相关联的表。

你能帮我找到为什么它不包含ownerType以获取有关加载查询的描述,我该如何解决这个问题?谢谢!

public class Product : EntityBase
{
    public virtual string Name { get; set; }
    public virtual IList<ProductDescription> Descriptions { get; set; }
}

public class ProductDescription : Description
{
    public virtual Product Product { get; set; }
}

public class Description : EntityBase
{
    public virtual string Name { get; set; }
    public virtual string ShortDescription { get; set; }
    public virtual string LongDescription { get; set; }
}


<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Test.Domain" assembly="Test.Domain">
    <class name="Test.Domain.Product, Test.Domain" table="Products">
        <id name="ID" column="ID" type="Int32" unsaved-value="0">
            <generator class="native" />
        </id>

        <property name="Name" />

        <bag name="Descriptions" inverse="true" cascade="all">
            <key column="OwnerID" />
            <one-to-many class="Test.Domain.ProductDescription, Test.Domain" />
        </bag>
    </class>
</hibernate-mapping>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Test.Domain" assembly="Test.Domain">
<class name="Test.Domain.Description, Test.Domain" table="Descriptions" discriminator-value="0">
        <id name="ID" column="ID" type="Int32" unsaved-value="0">
            <generator class="native" />
        </id>

        <discriminator column="OwnerType" />

        <property name="Name" />
        <property name="ShortDescription" />
        <property name="LongDescription" />

        <subclass name="Test.Domain.ProductDescription, Test.Domain" discriminator-value="1">
            <many-to-one name="Product" class="Test.Domain.Product, Test.Domain" column="OwnerID" not-null="true"></many-to-one>
        </subclass>
</class>
</hibernate-mapping>

1 个答案:

答案 0 :(得分:2)

在鉴别器映射上添加force = true

<discriminator column="OwnerType" force="true" />

这将确保将ownertype添加到查询