6

我想从 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>());
4

2 回答 2

8

算术运算符可通过VarArgsSQLFunctionSQL 函数用于条件查询。在您的特定情况下,这看起来像:

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 中,因此您需要确保底层数据库支持您使用的运算符。

于 2012-05-25T14:51:39.293 回答
2

使用 LINQ 或 HQL 很简单,但 Criteria 和 QueryOver 并没有为此优化(您必须使用 SQL 投影)

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)
于 2011-01-28T16:04:38.837 回答