Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any arithmetic operation projections in NHibernate?

I would like to get this SQL from NHibernate:

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>());
like image 224
Andrej Slivko Avatar asked Jan 28 '11 13:01

Andrej Slivko


1 Answers

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.

like image 149
Nathan Baulch Avatar answered Nov 13 '22 13:11

Nathan Baulch