我试图从带有 group by 的查询中获取计数,但不知道如何将我想要的 SQL 转换为 NHibernate 的 QueryOver 语法。
这是 SQL:
select count(*) from
(select Email from Entry
where (conditions...)
group by Email) as tmp
看起来很简单吧?
这就是我尝试执行的方法,但是 RowCount() 调用似乎完全优化了组:
var query = _unitOfWork.CurrentSession.QueryOver<ContestEntry>()
.Select(Projections.Property<ContestEntry>(x => x.Email),
Projections.Group<ContestEntry>(x => x.Email));
return query.RowCount();
我不介意为此使用 Criteria,但我对新的(对我来说)QueryOver API 感到兴奋,它让我摆脱了魔法字符串。
Update:
我无法使用生成的 SQL 在计数内执行不同的查询(例如 select count(distinct Email)),因为此应用程序在 SQL CE 上运行。
See: http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/80a1d7dd-22be-4583-b8f2-fcd8cde5ec53/ http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/80a1d7dd-22be-4583-b8f2-fcd8cde5ec53/ and http://our.umbraco.org/wiki/install-and-setup/sql-server-ce-4-known-issues http://our.umbraco.org/wiki/install-and-setup/sql-server-ce-4-known-issues(“不支持计数上的不同”,大约在页面下方的 2/3)
我不确定你为什么需要如此复杂的查询。如果您只想计算满足特定条件的不同电子邮件的数量,我认为您可以在 SQL 中使用类似的内容:
select count(distinct email)
from Entry
where (conditions...)
将其转换为 NHibernate 的 QueryOver API 看起来像这样:
int count = session.QueryOver<ContestEntry>()
.Select(Projections.CountDistinct<ContestEntry>(x => x.Email))
.FutureValue<int>()
.Value;//query is not executed until here
除非我遗漏了什么,否则我想这会得到你想要的结果。还有一个您可能会感兴趣的“Distinct”投影和 .ToRowCountQuery() 方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)