NHibernate:使用子集合的子集获取多个实体?
我的类看起来像这样(我只包含相关属性):
public class Order
{
public virtual Customer Customer { get; set; }
public virtual IEnumerable<OrderLine> OrderLines { get; set; }
}
public class OrderLine
{
public virtual string Product { get; set; } // Simplified
}
现在我想要的是创建一个独立的条件,选择给定客户的所有订单,同时仅检索每个订单的前 10 个 OrderLine。第一部分很简单:
Customer someCustomerObject = ...;
var criteria = DetachedCriteria.For<Order>().Add(Restrictions.Eq("Customer", someCustomerObject);
但是我如何指示 NHibernate 为按上述条件检索的每个订单急切地检索前 10 个订单行?
我尝试使用基于以下示例的过滤器(取自 Nhibernate 文档):
session.CreateFilter( lazyCollection, "").SetFirstResult(0).SetMaxResults(10).List();
但是当我将 Order.OrderLines
赋予 CreateFilter
方法时,它首先检索所有订单行,然后检索前 10 个订单行,这不是我想要的。我还尝试将其与对 NHibernateUtil.Initialize 的调用结合起来,但无济于事。
如何为这个问题创建一个独立的标准?或者,如果这不完全可能,如何为每个订单仅检索前 10 个结果,而不获取整个集合?
My classes look something like this (I include only the relevant properties):
public class Order
{
public virtual Customer Customer { get; set; }
public virtual IEnumerable<OrderLine> OrderLines { get; set; }
}
public class OrderLine
{
public virtual string Product { get; set; } // Simplified
}
Now I What I want is to create a detached criteria that selects all orders for a given customer, and at the same time retrieves only the first 10 OrderLines for each order. The first part is easy:
Customer someCustomerObject = ...;
var criteria = DetachedCriteria.For<Order>().Add(Restrictions.Eq("Customer", someCustomerObject);
But how do I instruct NHibernate to retrieve eagerly the first 10 orderlines for each order retrieved by the criteria above?
I've tried using a Filter based on the following example (taken from Nhibernate documentation):
session.CreateFilter( lazyCollection, "").SetFirstResult(0).SetMaxResults(10).List();
But when I give Order.OrderLines
to the CreateFilter
method, it retrieves all orderlines first, and then afterwards retrieves the 10 first orderlines, which is not what I want. I also tried combining this with a call to NHibernateUtil.Initialize
to no avail.
How do I create a detached criteria for this problem? Or, if that is not entirely possible, how to I retrieve, for each order, the 10 first results only, without fetching the entire collection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在 Order 类的 NHibernate 映射文件中将
batch-size
属性设置为 10。这样,它会急切地加载集合的前 10 个元素,并延迟加载其余元素。我将按如下方式映射该集合:更多信息,请阅读:NHibernate 映射 - 集合
You can set the
batch-size
property to 10 in the NHibernate mapping file for the Order class. This way it eagerly loads the first 10 elements of the collection and lazy-loads the rest of elements. I would map the collection as follows:More information, read on: NHibernate Mapping - Collections