开发者

nHibernate: limit the result set of a mapped collection

开发者 https://www.devze.com 2022-12-21 23:52 出处:网络
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, s

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.Item开发者_运维知识库s.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.


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.


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


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.

0

精彩评论

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