tags:

views:

96

answers:

2

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?

A: 

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.

Jamie Ide
+2  A: 

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

<class "Car" polymorphism="explicit" ...
dotjoe
Thanks!! Was hoping it would be as simple as that.
Dan