开发者

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

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="ParkedCa开发者_如何转开发r" xmlns="urn:nhibernate-mapping-2.2" table="tblParkedCar" >

How do I stop this?


I think you need to set the polymorphism property on the class mapping

<class "Car" polymorphism="explicit" ...


Since ParkedCar extends Car, a query for Car will return both Car and ParkedCar objects. You can restrict the type using HQL using the special class property, i.e. from Car c where c.class = Car. I don't think you can do this with the criteria API.

Alternatively you could filter the list after retrieving it if it's a reasonable size.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜