views:

3740

answers:

2

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?

+15  A: 

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.

mookid8000
+1. Huh that's pretty weird. I thought the answer would be part of the HQL "tunneled" string. Interesting.
tyndall
This answer is actually a hybrid of HQL and the criteria API
Ben Laan
yea..it's essentially the same as criteria...just replace with `CreateCriteria<SomeEntity>()`
dotjoe
any idea how to order the results before selecting the top 15?
kmehta
+6  A: 

Criteria API Method:

ICriteria criteria = DaoSession.CreateCriteria(typeof(T));
criteria.SetFirstResult(StartIndex);
criteria.SetMaxResults(MaximumObjects);
return criteria.List<T>();
+1. I'll have to look into this MaximumObjects. Pretty cool.
tyndall
MaximumObjects is just an integer variable to tell SetMaxResults how many objects to return. In your case, you could hard code 15 instead, i.e. criteria.SetMaxResults(15);
Haha... so in other words it is identical to CreateQuery() after the instance is created.
Andrew Burns