Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate: How to select the root entity in a projection

Ayende describes a really great way to get page count, and a specific page of data in a single query here:

http://ayende.com/blog/2334/paged-data-count-with-nhibernate-the-really-easy-way

His method looks like:

IList list = session.CreateQuery("select b, rowcount() from Blog b")
              .SetFirstResult(5)
              .SetMaxResults(10)
              .List();

The only problem is this example is in HQL, and I need to do the same thing in an ICriteria query. To achieve the equivalent with ICriteria, I need to do something like:

IList list = session.CreateCriteria<Blog>()
              .SetFirstResult(5)
              .SetMaxResults(10)
              .SetProjection(Projections.RootEntity(), Projections.SqlFunction("rowcount", NHibernateUtil.Int64))
              .List();

The problem is there is no such thing as Projections.RootEntity(). Is there any way to select the root entity as one of the projections in a projection list?

Yes, I know I could just use CriteriaTransform.TransformToRowCount() but that would require executing the query twice - once for the results and once for the row count. Using Futures may help a little by reducing it to one round-trip, but it's still executing the query twice on the SQL Server. For intensive queries this is unacceptable. I want to avoid the overhead, and return the row count and the results in the same query.

The basic question is: using ICriteria, is there any way to select the root entity AND some other projection at the same time?

EDIT: some related links:

https://nhibernate.jira.com/browse/NH-1372?jql=text%20~%20%22entity%20projection%22

https://nhibernate.jira.com/browse/NH-928

like image 999
jonh Avatar asked Nov 13 '22 08:11

jonh


1 Answers

I implemented a RootEntityProjection. You can try the code, which you can find at: http://weblogs.asp.net/ricardoperes/archive/2014/03/06/custom-nhibernate-criteria-projections.aspx. Let me know if it helped.

like image 84
Ricardo Peres Avatar answered Nov 15 '22 07:11

Ricardo Peres