views:

1254

answers:

2

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?

+4  A: 

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

Stuart Childs
unfortunately, this doesn't quite work how I wanted. The restriction is applied in the WHERE clause rather than in a having clause. The end result being that each individual row is restricted rather than the sum of all the rows.
lomaxx
Weird, I could swear I've used this before and it worked. Unfortunately, the best documentation I can find for it is the patch submission: http://nhjira.koah.net/browse/NH-1280.
Stuart Childs
thanks for the info... looks like we'll have to wait for 2.1.0 before this is supported. I believe it's built into Hibernate but NHibernate is still waiting
lomaxx
Ah, ok. I end up having to customize NHibernate a lot with stuff like this so I probably just applied that patch to my local build of the library. That would explain why it's not in the documentation though. ;)
Stuart Childs
Hmm. I just upgraded to 2.1.0 and the ProjectionCriteria method has disappeared.
madcapnmckay
I can't find my test case for HAVING... it's possible they just cleaned up the API and you no longer have to explicitly state the projection conditions as such through .ProjectionCriteria. SetProjection returns the criteria object so maybe you're just supposed to add restrictions via ICriteria's .Add.
Stuart Childs
My bad. It appears that this is only absent on the DetachedCriteria which I was using.
madcapnmckay
+1  A: 

For whomever drops by here with a similar problem, I just solved it this way:

IProjection howMany = Projections.Count("Id").As("HowMany");

ICriteria criteria = session
    .CreateCriteria<L10N>()
    .SetProjection(
        howMany,
        Projections.GroupProperty("Native"),
        Projections.GroupProperty("Locale")
    );

criteria.Add(Restrictions.Gt(howMany,1));
ANeves