tags:

views:

54

answers:

3

How do you limit the result set of a mapped collection in nHibernate? For instance:

Model.Items;

will always return all the Items for the given Model. Is there any way to force it to return only, say, 20 Items without creating a specific query ? Something like

Model.Items.SetMaxResults(20); 

In other words, I would like nHibernate to return IQueryable instead of a simple IList, when I access a collection.

Update. Although I have accepted the answer, I would like to point out that this is not in line with nHibernate's intended way of usage, and a child collection should be loaded and limited within a separate query.

+1  A: 

.SetProjection(Projections.Property("Items")) .SetMaxResults(20)

igor
That would work for ICriteria, not for the mapping.
HeavyWave
using System.Linq; IList results = session.CreateCriteria(typeof(Model)) .SetProjection(...).list();IQueryable q = results.AsQueryable();
igor
Nhibernate has this parameter for mapping collections <batch-size="N">. But it seems, this is something different that you want, I think. So only Criteria allows to control fetching records dynamically.
igor
A: 

Yes, you can use the <loader /> mapping element to specify a query that will load the collection. More information can be found here and here.

Jamie Ide
This is cool, but it won't let me specify parameters for LIMIT at the point of access to the collection, which is what I would like to have.
HeavyWave
A: 

What you want can be accomplished with a filter:

IQuery q = nhSession.CreateFilter(Parent.ChildCollection, "select count(*)");
long countResult = q.UniqueResult<long>();

as you see the filter in an IQuery and you are not limited to the "select count" paradigm i just gave. Additionally, this solution requires a normal collection mapped so you can use it in multiple ways.

Jaguar