Are there any arithmetic operation projections in NHibernate?

与世无争的帅哥 提交于 2019-11-30 07:30:49

Arithmetic operators can be used in criteria queries via the VarArgsSQLFunction SQL function. 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.

It's trivial with LINQ or HQL, but Criteria and QueryOver are not optimized for that (you have to use a SQL Projection)

HQL is almost the same as SQL:

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

LINQ is not hard either:

from entry in Session.Query<ConnectorLogEntry>()
group entry by entry.DepartmentName into g
select g.Sum(e => e.ColorPages) * g.Sum(e => e.TotalPages)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!