nHibernate 计算子查询中的行数

发布于 2024-12-14 06:19:00 字数 889 浏览 1 评论 0原文

我怎样才能在nHibernate中做这样的事情:

select count(*)
from (subquery)

这是一个相当简单的SQL查询,但在nHibernate中解决方案并不那么明显。一个明显的解决方案是:

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

但是,这会导致 ArgumentOutOfRangeException

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

这个所以答案对我不起作用,因为我有一个更复杂的分组。 我的问题源自一个较早的问题,我尝试使用ToRowCountQuery,但该函数会从查询中剥离分组。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

起风了 2024-12-21 06:19:00

一旦您有了会话,您就可以

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

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

Once you have a session, you could

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

int count = (int) criteria.UniqueResult();
请远离我 2024-12-21 06:19:00

我发现 Ayende 的一篇旧帖子给了我一个解决方案(计算分页数据)。

我按照该帖子中的描述创建了自己的方言,并将 rowcount 函数添加到我的分页查询中。很快,我就在对数据库的单个查询中获得了行计数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文