NHibernate, Sum Query

Dan picture Dan · Sep 15, 2008 · Viewed 9.1k times · Source

If i have a simple named query defined, the preforms a count function, on one column:

  <query name="Activity.GetAllMiles">
    <![CDATA[
      select sum(Distance) from Activity
    ]]>

  </query>

How do I get the result of a sum or any query that dont return of one the mapped entities, with NHibernate using Either IQuery or ICriteria?

Here is my attempt (im unable to test it right now), would this work?

    public decimal Find(String namedQuery)
    {
        using (ISession session = NHibernateHelper.OpenSession())
        {
            IQuery query = session.GetNamedQuery(namedQuery);


            return query.UniqueResult<decimal>();
        }
    }

Answer

Matt Hinze picture Matt Hinze · Sep 16, 2008

As an indirect answer to your question, here is how I do it without a named query.

var session = GetSession();
var criteria = session.CreateCriteria(typeof(Order))
            .Add(Restrictions.Eq("Product", product))
            .SetProjection(Projections.CountDistinct("Price"));
return (int) criteria.UniqueResult();