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

ぃ、小莉子 提交于 2019-12-04 15:34:15

问题


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?


回答1:


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.




回答2:


Criteria API Method:

ICriteria criteria = DaoSession.CreateCriteria(typeof(T));
criteria.SetFirstResult(StartIndex);
criteria.SetMaxResults(MaximumObjects);
return criteria.List<T>();



回答3:


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



回答4:


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.




回答5:


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!



来源:https://stackoverflow.com/questions/555045/nhibernate-hqls-equivalent-to-t-sqls-top-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!