sqlhibernatenhibernateaggregatenative-sql

nhibernate native sql get aggregate value


I need to execute native sqn on nhibernate and get sum from complex query needed for reporting. The sql query returns only one float value for a sum.

float theSum= session.CreateSQLQuery(@"select sum(myfield) myfield from ....")
                               .AddScalar("myfield", NHibernateUtil.Single)
                               .UniqueResult<float>();

Is this OK ?
Is there any other way to do this ? I guess this auto casts null value to 0.


Solution

  • I've double checked the code, and it does contain an explicit conversion of null to 0 - you should use <float?> if you want to see/act on the difference between 0 and null.

    You might also want to look at named queries as an alternative: http://nhibernate.info/doc/nh/en/index.html#querysql-namedqueries