Using nHibernate to map two different data models to one entity model

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2010-05-14T15:18:16Z Indexed on 2010/05/14 18:44 UTC
Read the original article Hit count: 209

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about hbm