2

我有两个不同的数据模型映射到同一个 Car 实体。我需要创建第二个名为 ParkedCar 的实体,它与 Car 相同(因此继承自它),以阻止 nhibernate 抱怨同一实体存在两个映射。

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
}

唯一的问题是,当我使用 Criteria API 从数据库中检索 Car 时,如下所示:

SessionProvider.OpenSession.Session.CreateCriteria<Car>()
                    .Add(Restrictions.Eq("Id", 123))
                    .List<Car>();

该查询带回来自 ParkedCar 数据模型的汽车实体。好像 nhibernate 默认为专门的实体。并且映射在正确的地方寻找:

<class name="Car" xmlns="urn:nhibernate-mapping-2.2" table="tblCar">

<class name="ParkedCar" xmlns="urn:nhibernate-mapping-2.2" table="tblParkedCar" >

我该如何阻止这个?

4

2 回答 2

3

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

<class "Car" polymorphism="explicit" ...
于 2010-05-14T18:41:42.867 回答
0

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.

于 2010-05-14T18:13:35.260 回答