Loading a base class through nhibernate incorrectl

2019-08-09 09:51发布

问题:

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