Loading a base class through nhibernate incorrectly uses mappings from derived classes

狂风中的少年 提交于 2019-12-13 01:58:22

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/4550188/loading-a-base-class-through-nhibernate-incorrectly-uses-mappings-from-derived-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!