【问题标题】:NHibernate subclasses and composite keysNHibernate 子类和组合键
【发布时间】:2009-12-21 03:28:31
【问题描述】:

我有一个 StoreHours 类,它有一个复合键并且一直运行良好。一个新的要求出现了,要求返回另一种类型的时间。我想“很简单,我将抽象基类,有两个具体的实现,并将我在应用程序中的引用更改为新类之一”。但是,这样做后,我的单元测试失败了

X.Test.StoreTest.HoursTest:NHibernate.InstantiationException:无法实例化抽象类或接口:X.Model.StoreHours

我的映射文件看起来像

<class name="StoreHours" table="StoreHour" abstract="true" discriminator-value="0" >
    <composite-id>
        <key-many-to-one name="Store"
            class="Store"
            column="StoreUid"/>
        <key-property name="DayOfWeek" 
            column="DayOfWeekId"
            type="System.DayOfWeek" />
    </composite-id>
    <discriminator column="StoreHourType" type="Byte" />
    <property name="OpenMinutes" column="OpenTime" />
    <property name="CloseMinutes" column="CloseTime" />
    <subclass name="OfficeHours" discriminator-value="1" />
    <subclass name="AccessHours" discriminator-value="2" />
</class>

我找到了有类似问题的人here 并开始了他们的解决方案,但实际上最终遇到的问题比我开始时还要多。

我可以完美地将记录保存到数据库中,但在加载时,NHibernate 正在尝试实例化抽象的“StoreHours”,即使我只有一个强类型设置“OfficeHours”

这似乎是一个非常微不足道的要求,所以我认为我一定是在做一些简单的错误。感谢所有提示。

【问题讨论】:

    标签: nhibernate subclass composite-id


    【解决方案1】:

    The problem is in the way you are using the composite-id

    Table-per-class 与 Composite-id 一起使用,但仅当复合是 作为一个类实现

    所以你需要创建一个类

    public class StoreHoursCompositeId
     {
            public virtual Store Store { get; set; }
            public virtual DayOfWeek DayOfWeek { get; set; }
    
            // Implement GetHashCode(), is NH-mandatory
            // Implement Equals(object obj), is NH-mandatory
    }
    

    在您的 StoreHours 对象中创建一个使用上述类的属性(在我的示例中,我将其称为“StoreHoursCompositeId”)

    你的映射变成:

    <class name="StoreHours" table="StoreHour" abstract="true" discriminator-value="0" >
        <composite-id name="StoreHoursCompositeId" class="StoreHoursCompositeId">
            <key-many-to-one name="Store" class="Store"
                column="StoreUid"/>
            <key-property name="DayOfWeek" 
                column="DayOfWeekId"
                type="System.DayOfWeek" />
        </composite-id>
        <discriminator column="StoreHourType" type="Byte" />
        <property name="OpenMinutes" column="OpenTime" />
        <property name="CloseMinutes" column="CloseTime" />
        <subclass name="OfficeHours" discriminator-value="1" />
        <subclass name="AccessHours" discriminator-value="2" />
    </class>
    

    我遇到了同样的问题,这为我解决了问题。

    【讨论】:

    • 令人着迷。希望这会对某人有所帮助。不幸的是,对我来说已经晚了大约 4.5 年 :) 没有尝试就将其标记为正确答案。就我而言,我的回答完全是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多