Question

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>();
        }
    }
Was it helpful?

Solution 2

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>();
            }

OTHER TIPS

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();

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top