流畅的 nhibernate 与基类一对一
假设我有类:
class Person
{
String FirstName;
String LastName;
Pet Pet;
}
class Pet
{
String Name;
Person Owner;
}
class Cat : Pet
{
Int32 MousesCaught;
}
class Dog : Pet
{
Int32 CatsCaught;
}
和映射:
public class PetMap : IAutoMappingOverride<Pet>
{
public void Override(AutoMapping<Pet> mapping)
{
mapping.HasOne(x => x.Owner).PropertyRef(x => x.Pet).Constrained().Cascade.All();
mapping.JoinedSubClass<Cat>("PetId");
mapping.JoinedSubClass<Dog>("PetId");
}
}
问题是:如果数据库中存在有猫或狗的人,则 Person.Pet 的类型为“Pet{PetBroxyBlaBlaBla}”。所以我不能将 Person.Pet 转换为 Cat (Person.Pet as Cat == null)。
var person = this.Session.Get<Person>(personId);
// person.Pet as Cat == null
但是,如果我在获取 Person 之前从数据库获取此宠物,则类型是有效的:
var a = new this.Session.Get<Pet>(petId);
var person = this.Session.Get<Person>(personId);
// person.Pet as Cat != null
有没有办法告诉 NHibernate使用有效类型初始化此属性?
Suppose I have classes:
class Person
{
String FirstName;
String LastName;
Pet Pet;
}
class Pet
{
String Name;
Person Owner;
}
class Cat : Pet
{
Int32 MousesCaught;
}
class Dog : Pet
{
Int32 CatsCaught;
}
And a mapping:
public class PetMap : IAutoMappingOverride<Pet>
{
public void Override(AutoMapping<Pet> mapping)
{
mapping.HasOne(x => x.Owner).PropertyRef(x => x.Pet).Constrained().Cascade.All();
mapping.JoinedSubClass<Cat>("PetId");
mapping.JoinedSubClass<Dog>("PetId");
}
}
The problem is: if there is Person with a Cat or a Dog in the DB the type of the Person.Pet is 'Pet{PetBroxyBlaBlaBla}'. So I cannot cast Person.Pet to type Cat (Person.Pet as Cat == null).
var person = this.Session.Get<Person>(personId);
// person.Pet as Cat == null
But if I get this pet from DB before getting a Person the type is valid:
var a = new this.Session.Get<Pet>(petId);
var person = this.Session.Get<Person>(personId);
// person.Pet as Cat != null
Is there are a way to tell NHibernate to init this property with a valid type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试禁用延迟加载。它可能是由 这个
Try disabling lazy loading. It can be caused by this