Monday 24 September 2007

NHibernate Criteria aggregate (Sum,Max etc)

It is possible to get NHibernate criteria to perform aggregations using the Projections class:

 


public double SumHours(out double chargeable, out double nonchargeable)
        {
            IList results;
            ICriteria crit = _session.CreateCriteria(typeof(Activity));
            ProjectionList projList = Projections.ProjectionList();
            projList.Add(Projections.Sum("ChargeableHours"));
            projList.Add(Projections.Sum("NonChargeableHours"));

            crit.SetProjection(projList);
            results=crit.List();
            if (results.Count == 0)
            {
                chargeable = 0;
                nonchargeable = 0;
            }
            else
            {
                chargeable = (double)(results[0] as object[])[0];
                nonchargeable = (double)(results[0] as object[])[1];
            }

            return chargeable + nonchargeable;
        }