使用 nHibernate 将两种不同的数据模型映射到一个实体模型
我有两个不同的数据模型映射到同一个汽车实体。我需要创建第二个名为 ParkedCar 的实体,它与 Car 相同(因此继承自 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 从数据库中检索汽车时,如下所示:
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" >
我该如何阻止这种情况?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您需要在 类映射< /a>
I think you need to set the polymorphism property on the class mapping
由于 ParkedCar 扩展了 Car,因此对 Car 的查询将返回 Car 和 ParkedCar 对象。您可以使用 特殊类属性,即
来自 Car c,其中 c.class = Car
。我不认为你可以使用标准 API 来做到这一点。或者,如果列表大小合理,您可以在检索列表后对其进行过滤。
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.