Search code examples
c#nhibernateicriteria

NHibernate Projections and "Having" clause


I'm using NHibernate to query my database with the criteria API. My criteria is below:

ICriteria c = Session.CreateCriteria(typeof(Transaction));

ProjectionList projections = Projections.ProjectionList();
projections.Add(Projections.Sum("Units"), "Units");
projections.Add(Projections.GroupProperty("Account"), "Account");
projections.Add(Projections.GroupProperty("Security"), "Security");
c.SetProjection(projections);

This is working fine, but what I would like is a way to be able to limit the query to only return when the "Units" property is > 0. In SQL I would simply us a Having Units > 0 clause however I haven't been able to find a way to do this in NHibernate. Does anyone have any ideas or is my only option to use HQL?


Solution

  • You can access the ProjectionCriteria from the Criteria object.

    ...
    c.SetProjection(projections)
    .ProjectionCriteria
    .Add(Restrictions.Ge("Units", 0));
    

    EDIT: This solution doesn't currently work, however it should work in NHibernate 2.1.0