通过nhibernate加载基类错误地使用派生类的映射 [英] Loading a base class through nhibernate incorrectly uses mappings from derived classes

查看:163
本文介绍了通过nhibernate加载基类错误地使用派生类的映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我有一个基类作为一个实体,然后是另一个实体,从另一个基类派生。

  public class MyBaseClass 
{
int ID {get;组; }
string Name {get;组; }
}

public class MyChildClass
{
string AdditionalField {get;组; }
}

我使用Fluent nHibernate使用ClassMap进行映射,如下所示:

  public class MyBaseClassMap:ClassMap< MyBaseClass> 
{
Id(MyBaseClassID);
Map(x => x.Name);
}

public class MyChildClassMap:SubclassMap< MyChildClass>
{
Map(x => x.AdditionalField);

$ / code>

当我尝试获取基类的副本时,它使用映射的子类。它好像不知道基类和子类之间的区别,或者它选择了错误的映射。我通过观察SQL语句并将其加入到子表中并获取附加列来证实了这一点。任何方式来使用正确的地图?

解决方案

这是NHibernate的'性质'。
你描述的行为被称为多态查询。由于 MyChildClass 是一个 MyBaseClass ,MyChildClass实例如果你想避免这种行为,你也许可以看一下中的答案。 / questions / 2093025 / how-to-perform-a-non-polymorphic-hql-query-in-hibernate>这个话题。 (我从来没有禁用多态查询能力)。


I have a scenario where I have a base class as one entity, then another entity that derives from the other base class. Both have meaning in my domain and can be used separately.

public class MyBaseClass
{
    int ID { get; set; }
    string Name { get; set; }
}

public class MyChildClass
{
    string AdditionalField { get; set; }
}

I have both mapped using Fluent nHibernate using ClassMap like this:

public class MyBaseClassMap : ClassMap<MyBaseClass>
{
   Id("MyBaseClassID");
   Map(x => x.Name);
}

public class MyChildClassMap : SubclassMap<MyChildClass>
{
   Map(x => x.AdditionalField);
}

What is happening is when I try to fetch a copy of the base class, its using the mapping for the child class. Its as if it doesn't know the the difference between the base and child class, or its choosing the wrong mapping for it. I confirmed this by watching the SQL statement and its joining to the child table and fetching the additional column. Any way to get it to use the right map?

解决方案

That's the 'nature' of NHibernate.
The behaviour you're describing, is called 'polymorphic queries'.

Since MyChildClass is a MyBaseClass, the MyChildClass instances are retrieved as well.

If you want to avoid this behaviour, you can maybe have a look at the answers in this topic. (I've never 'disabled' the polymorphic query ability).

这篇关于通过nhibernate加载基类错误地使用派生类的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆