In short: Given an aggregate query (one with Max, Min, Count, etc) in NHibernate, how can you modify the query to also return the full record associated with the aggregated value?
My example: I have 2 tables: People (primary key: PersonId) with a 1-to-many relationship to Events (primary key: EventId; other columns: PersonId, EventDate).
I want to select the last event per person and generate a list of these events. The SQL for last event per person would be something like SELECT PersonId, Max(EventDate) FROM ... GROUP BY PersonId. So far the NHibernate query looks like:
ICriteria criteria = session.CreateCriteria<Event>()
.SetProjection(Projections.ProjectionList()
.Add(Projections.GroupProperty("PersonId"))
.Add(Projections.Max("EventDate"))
);
Now what I really need is the full event info. One solution, in theory, is to essentially join the above criteria to the Events table by PersonId and the max EventDate (easy enough in plain SQL). However I’m at a loss of how to perform this in NHibernate.
I’m open to any suggestion (HQL, LINQ, etc.) so long as it avoids stored procedures and views and is limited to 1 or just a few queries. Issuing a query per Person will not be scalable or performant in my case.
I hope you are also open to QueryOver (this can be converted to ICriteria)…