我想从NHibernate获取这个SQL:
SELECT SUM(color_pages) * SUM(total_pages)
FROM connector_log_entry
GROUP BY department_name
但我无法在任何地方找到任何算术运算(*)投影。
这是我到目前为止的代码:
Session.QueryOver<ConnectorLogEntry>()
.SelectList(list => list
.SelectGroup(m => m.DepartmentName)
.WithAlias(() => dto.Department)
.Select(Projections.Sum<ConnectorLogEntry>(m => m.TotalPages))
//.Select(Projections.Sum<ConnectorLogEntry>(m => m.ColorPages))
.WithAlias(() => dto.TotalColorPercentage))
.TransformUsing(Transformers.AliasToBean<DepartmentConsumption>());
答案 0 :(得分:8)
算术运算符可以通过VarArgsSQLFunction
SQL函数用于条件查询。在您的特定情况下,这看起来像:
Session.QueryOver<ConnectorLogEntry>()
.SelectList(list =>
list.SelectGroup(m => m.DepartmentName)
.WithAlias(() => dto.Department)
.Select(Projections.SqlFunction(
new VarArgsSQLFunction("(", "*", ")"),
NHibernateUtil.Int32,
Projections.Sum<ConnectorLogEntry>(m => m.TotalPages),
Projections.Sum<ConnectorLogEntry>(m => m.ColorPages)))
.WithAlias(() => dto.TotalColorPercentage))
.TransformUsing(Transformers.AliasToBean<DepartmentConsumption>());
此技术将字符串直接注入生成的SQL中,因此您需要确保底层数据库支持您使用的运算符。
答案 1 :(得分:2)
使用LINQ或HQL很简单,但是Criteria和QueryOver没有针对它进行优化(你必须使用SQL Projection)
HQL与SQL几乎相同:
select sum(ColorPages) * sum(TotalPages)
from ConnectorLogEntry
group by DepartmentName
LINQ也不难:
from entry in Session.Query<ConnectorLogEntry>()
group entry by entry.DepartmentName into g
select g.Sum(e => e.ColorPages) * g.Sum(e => e.TotalPages)