如何使用 NHIbernate 将未持久化的对象附加到从数据库加载的对象
我有一个如下所示的实体:
public class Driver
{
IVehicle Vehicle {get;set;}
}
以及实现 IVehicle 的几个不同类(汽车、自行车、火车...)
我如何选择我的驱动程序持有的 IVehicle 的特定实现,并在下次加载驱动程序时记住此选择来自数据库?
我使用 NHibernate 3.0 进行持久化,并使用 FluentNHibernate 进行映射。
编辑
好吧,我终于想通了。我需要按以下方式映射车辆并映射每个子类:
public void VehicleMap : ClassMap<IVehicle>
{
public VehicleMap()
{
Id(v => v.Id); // Needed to add a property which will be used as Id
DiscriminateSubClassesOnColumn("TYPE");
}
}
public void CareMap : SubclassMap<Car>
{
public CarMap()
{
DiscriminatorValue("CAR");
}
}
此外,我需要从驱动程序映射中禁用车辆的延迟加载
I have an entity which looks likes this:
public class Driver
{
IVehicle Vehicle {get;set;}
}
and several different classes which implement IVehicle (Car, Bike, Train...)
How can I select which specific implementation of IVehicle my Driver holds, and remember this selection the next time I load the driver from the DB?
I'm using NHibernate 3.0 for persistence together with FluentNHibernate for mapping.
EDIT
Ok I figured it out finally. I needed to map the vehicle and to map each subclass in the following way:
public void VehicleMap : ClassMap<IVehicle>
{
public VehicleMap()
{
Id(v => v.Id); // Needed to add a property which will be used as Id
DiscriminateSubClassesOnColumn("TYPE");
}
}
public void CareMap : SubclassMap<Car>
{
public CarMap()
{
DiscriminatorValue("CAR");
}
}
Additionally, I needed to disable lazy loading of the Vehicle from the driver mapping
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要决定您的继承映射将如何工作。请参阅文档 http://nhibernate.info/doc/nh/en/index。 html#inheritance
完成后,您可以映射 Driver 类以级联 Vehicle 依赖项。之后,NHibernate 将自动从数据库加载正确的项目。
更新
您需要将类型名称保留为字符串。那么您的 Vehicle 类可以是一个未映射的属性,其功能如下:
You need to decide how your inheritance mapping will work. See the documentation http://nhibernate.info/doc/nh/en/index.html#inheritance
Once you do, you can map your Driver class to cascade the Vehicle dependency. After that point NHibernate will automatically load the proper item from the database.
UPDATE
You will need to persist the type name as a string. Then your Vehicle class can be an unmapped property that does something like: