views:

2748

answers:

3

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>();
        }
    }
+2  A: 

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();
Matt Hinze
A: 

Sorry! I actually wanted a sum, not a count, which explains alot. Iv edited the post accordingly

This works fine:

var criteria = session.CreateCriteria(typeof(Activity))
                          .SetProjection(Projections.Sum("Distance"));
   return (double)criteria.UniqueResult();

The named query approach still dies, "Errors in named queries: {Activity.GetAllMiles}":

 using (ISession session = NHibernateHelper.OpenSession())
            {
                IQuery query = session.GetNamedQuery("Activity.GetAllMiles");


                return query.UniqueResult<double>();
            }
Dan
A: 

I think in your original example, you just need to to query.UniqueResult(); the count will return an integer.

Ben Scheirman