NHibernate HQL's Equivalent to T-SQL's TOP

2019-03-22 18:23发布

What is NHibernate HQL's Equivalent to T-SQL's TOP Keyword?

Also what is the non-HQL way for saying give me the first 15 of a class?

5条回答
迷人小祖宗
2楼-- · 2019-03-22 18:47

It's actually pretty easy in HQL:

var top15 = session.CreateQuery("from SomeEntity")
                .SetFirstResult(0)
                .SetMaxResults(15)
                .List<SomeEntity>();

Don't know how to do this using the criteria API though.

查看更多
【Aperson】
3楼-- · 2019-03-22 19:03

mookid8000 is giving false information.

there is no way of setting SQL TOP N with HQL :(

it always downloads all of the table to .NET and the takes the TOP, wich is just plain stupid!

查看更多
4楼-- · 2019-03-22 19:05

From NHibernate 3.2 you could use SKIP n / TAKE n in hql at the end of the query. It could be very helpful in subqueries where you can not use SetMaxResults.

For example:

select l, (select u from User u where u.Location = l order by u.Date asc take 1) 
from Location l
查看更多
做自己的国王
5楼-- · 2019-03-22 19:05

For completeness, here is how to do it with the QueryOver API introduced in NHibernate 3.0:

var top15 = session.QueryOver<SomeEntity>().Take(15).List();

Throw in a .Skip(someInt) if you need to define a start index, e.g. for paging.

查看更多
成全新的幸福
6楼-- · 2019-03-22 19:11

Criteria API Method:

ICriteria criteria = DaoSession.CreateCriteria(typeof(T));
criteria.SetFirstResult(StartIndex);
criteria.SetMaxResults(MaximumObjects);
return criteria.List<T>();
查看更多
登录 后发表回答