nHibernate count rows in subquery

不打扰是莪最后的温柔 提交于 2019-12-24 08:05:03

问题


How can I do something like this in nHibernate:

select count(*)
from (subquery)

It is a rather simple query in SQL, but the solution is not so obvious in nHibernate. An obvious solution would be something along the line of:

    var rowcount = Session.QueryOver<Entity>()
       .Select(Projections.Alias(Projections.Count(Projections.SubQuery(detachedQuery)), "count"))
        .FutureValue<int>();

However, this results in an ArgumentOutOfRangeException:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

This SO answer doesn't work for me, as I have a more complex grouping. My question originates from an earlier question where I tried to use ToRowCountQuery, but that function strips groupings form the query.


回答1:


Once you have a session, you could

var criteria = session.CreateCriteria(....)

int count = (int) criteria.UniqueResult();



回答2:


I found an old post by Ayende which gave me a solution (Counting paged data).

I created my own dialect as described in that post and added the rowcount function to my paged query. And presto, I got my rowcount in a single query to the database.



来源:https://stackoverflow.com/questions/8047600/nhibernate-count-rows-in-subquery

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