开发者

NHibernate: getting multiple entities with subset of child collection?

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?


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:

<set name="OrderLines" table="OrderToOrderLine" batch-size="10">
    <key column="OrderId"/>
    <one-to-many class="OrderLine"/>
</set>

More information, read on: NHibernate Mapping - Collections

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜