简体   繁体   English

NHibernate中有任何算术运算预测吗?

[英]Are there any arithmetic operation projections in NHibernate?

I would like to get this SQL from NHibernate: 我想从NHibernate获取这个SQL:

SELECT SUM(color_pages) * SUM(total_pages)
FROM connector_log_entry
GROUP BY department_name

But I can't find any arithmetic operation (*) projections anywhere. 但我无法在任何地方找到任何算术运算(*)投影。

This is the code that I have so far: 这是我到目前为止的代码:

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>());

Arithmetic operators can be used in criteria queries via the VarArgsSQLFunction SQL function. 算术运算符可以通过VarArgsSQLFunction SQL函数用于条件查询。 In your particular case, this would look something like: 在您的特定情况下,这看起来像:

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>());

This technique injects strings directly into the generated SQL, so you'll need to make sure the underlying database supports the operators you use. 此技术将字符串直接注入生成的SQL中,因此您需要确保底层数据库支持您使用的运算符。

It's trivial with LINQ or HQL, but Criteria and QueryOver are not optimized for that (you have to use a SQL Projection) 使用LINQ或HQL很简单,但是Criteria和QueryOver没有针对它进行优化(你必须使用SQL Projection)

HQL is almost the same as SQL: HQL与SQL几乎相同:

select sum(ColorPages) * sum(TotalPages)
from ConnectorLogEntry
group by DepartmentName

LINQ is not hard either: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM