NHibernate表每类加载 - 错误的类型

时间:2011-10-10 13:35:08

标签: nhibernate fluent-nhibernate nhibernate-mapping fluent-nhibernate-mapping

我在Fluent / NHibernate中有每个类的表层次结构的映射问题。从数据库中检索记录时,我不断收到错误(错误的类型异常)

ID为2445763的对象不属于指定的子类:ClassA(加载对象的类别为[ClassB])(记录2445763在“类型”列中的值为“2”)

在我的域名中,我有EntryBase,ClassA和ClassB。这些类定义为

public abstract class EntryBase 
{
    public virtual int Id {get;set;}
    public virtual string CommonProperty1 {get;set;}
    *... (lots of other common properties)*
    public virtual string CommonPropertyN {get;set;}
}

public class ClassA : EntryBase 
{
    public virutal string ClassAOnlyProperty {get;set;}
}

public class ClassB : EntryBase 
{
    public virutal string ClassBOnlyProperty {get;set;}
    public virutal int ClassBOnlyOtherProperty {get;set;}
}

映射是:

public class EntryBaseMap : ClassMap<EntryBase>
{
    public EntryBaseMap()
    {
        Table("MySingleTable");
        Id(x => x.Id, "RecordId").GeneratedBy.Identity();
        Map(x => x.CommonProperty1, "Field1Name");
        ...
        Map(x => x.CommonPropertyN, "FieldNName");
        DiscriminateSubClassesOnColumn<string>("Type");
    }
}

public class ClassAMap : SubclassMap<ClassA>
{   
    public ClassAMap()
    {
        DiscriminatorValue("1");
        Map(x => x.ClassAOnlyProperty);
    }
}

public class ClassBMap : SubclassMap<ClassB>
{   
    public ClassBMap()
    {
        DiscriminatorValue("2");
        Map(x => x.ClassBOnlyProperty);
        Map(x => x.ClassBOnlyOtherProperty);
    }
}

知道可能有什么不妥吗?我已经正确地存储了B类记录,但是当我检索它们时,它正试图将它们加载为A类。它是映射问题吗?

1 个答案:

答案 0 :(得分:6)

正如评论中所讨论的,如果您有要表示单个子类的集合属性,则需要在映射中添加where子句:

.Where("Type = '1'")

Type是您的鉴别器列,1是与您尝试加载的类型匹配的鉴别器值。