How to attach an object which is not persisted to an object loaded from DB using NHIbernate
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");
开发者_如何学Go }
}
Additionally, I needed to disable lazy loading of the Vehicle from the driver mapping
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:
public class Driver
{
private string vehicleTypeName;
private IVehicle vehicle;
public IVehicle Vehicle
{
get
{
if (vehicle == null)
{
vehicle = typeof(IVehicle).Assembly
.CreateInstance(vehicleTypeName);
}
return vehicle;
}
}
}
精彩评论