NHibernate QueryOver:在子查询中获取group by的行计数

mma*_*lay 12 nhibernate queryover

我试图从一个group by的查询得到一个计数,但是无法弄清楚如何将我想要的SQL转换为NHibernate的QueryOver语法.

这是SQL:

select count(*) from
       (select Email from Entry
       where (conditions...)
       group by Email) as tmp
Run Code Online (Sandbox Code Playgroud)

好像很简单吧?

这就是我尝试这样做的方式,但RowCount()调用似乎完全彻底地优化了组:

    var query = _unitOfWork.CurrentSession.QueryOver<ContestEntry>()
        .Select(Projections.Property<ContestEntry>(x => x.Email),
                Projections.Group<ContestEntry>(x => x.Email));

    return query.RowCount();
Run Code Online (Sandbox Code Playgroud)

我不介意使用Criteria,但我很高兴新的(对我而言)QueryOver API可以让我摆脱魔法字符串.

更新:

我无法使用在计数内执行独特查询的生成SQL(例如,选择计数(不同的电子邮件)),因为此应用程序在SQL CE上运行.

请参阅:http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/80a1d7dd-22be-4583-b8f2-fcd8cde5ec53/http://our.umbraco.org/wiki/install-and -setup/sql-server-ce-4-known-issues("不支持计数不同",约为页面的2/3)

Ale*_*use 15

我不确定你为什么需要这么复杂的查询.如果您只想要满足特定条件的不同电子邮件的数量,我认为您可以在SQL中使用类似的内容:

select count(distinct email)
from Entry
where (conditions...)
Run Code Online (Sandbox Code Playgroud)

将其转换为NHibernate的QueryOver API看起来像这样:

int count = session.QueryOver<ContestEntry>()
            .Select(Projections.CountDistinct<ContestEntry>(x => x.Email))
            .FutureValue<int>()
            .Value;//query is not executed until here
Run Code Online (Sandbox Code Playgroud)

除非我遗漏了什么,否则我认为这会得到你所追求的结果.还有一个"Distinct"投影和.ToRowCountQuery()方法,你可能会觉得有趣.