通过 nhibernate 加载基类错误地使用了派生类的映射
我有一个场景,其中我有一个基类作为一个实体,然后是从另一个基类派生的另一个实体。两者在我的领域中都有意义并且可以单独使用。
public class MyBaseClass
{
int ID { get; set; }
string Name { get; set; }
}
public class MyChildClass
{
string AdditionalField { get; set; }
}
我都使用 Fluent nHibernate 使用 ClassMap 进行映射,如下所示:
public class MyBaseClassMap : ClassMap<MyBaseClass>
{
Id("MyBaseClassID");
Map(x => x.Name);
}
public class MyChildClassMap : SubclassMap<MyChildClass>
{
Map(x => x.AdditionalField);
}
发生的情况是,当我尝试获取基类的副本时,它使用子类的映射。就好像它不知道基类和子类之间的区别,或者为其选择了错误的映射。我通过观察 SQL 语句及其与子表的连接并获取附加列来确认这一点。有什么办法让它使用正确的地图吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是 NHibernate 的“本质”。
您所描述的行为称为“多态查询”。
由于
MyChildClass
是MyBaseClass
,因此也会检索 MyChildClass 实例。如果您想避免这种行为,您可以查看 此主题。 (我从未“禁用”多态查询能力)。
That's the 'nature' of NHibernate.
The behaviour you're describing, is called 'polymorphic queries'.
Since
MyChildClass
is aMyBaseClass
, 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).