Using nHibernate to map two different data models to one entity model
- by Dan
I have two different data models that map to the same Car entity. I needed to create a second entity called ParkedCar, which is identical to Car (and therefore inherits from it) in order to stop nhibernate complaining that two mappings exists for the same entity.
public class Car
{
protected Car()
{
IsParked = false;
}
public virtual int Id { get; set; }
public bool IsParked { get; internal set; }
}
public class ParkedCar : Car
{
public ParkedCar()
{
IsParked = true;
}
//no additional properties to car, merely exists to support mapping and signify the car is parked
}
The only issue is that when I come to retrieve a Car from the database using the Criteria API like so:
SessionProvider.OpenSession.Session.CreateCriteria<Car>()
.Add(Restrictions.Eq("Id", 123))
.List<Car>();
The query brings back Car Entities that are from the ParkedCar data model. Its as if nhibernate defaults to the specialised entity. And the mappings are defiantly looking in the right place:
<class name="Car" xmlns="urn:nhibernate-mapping-2.2" table="tblCar">
<class name="ParkedCar" xmlns="urn:nhibernate-mapping-2.2" table="tblParkedCar" >
How do I stop this?