Search code examples
nhibernategroup-bysubqueryicriteria

Getting the newest post from a topic using ICriteria (Nhibernate)


In a forum, I want to list the most recent posts from each topic. In SQL I can do a subquery with group by Topic taking Max(Post.Date) and then make an inner join with the Posts table to get the latest Post record from each Topic. How can I reproduce this in ICriteria?

DETAIL: The Topic class have NO Posts property.

TARGET SQL: SELECT Post.* FROM Posts, (SELECT IdTopic, MAX(DATE) AS Date FROM Posts GROUP BY IdTopic) AS MaxDates WHERE MaxDates.IdTopic = Posts.IdTopic AND MaxDates.Date = Posts.Date

Tks[]

Patrick Coelho


Solution

  • By using CreateCriteria. This is explained very well by Ayende Rahien.

    Edit changed to address OP's comments

    I'm on shaky ground here, but this may get you started:

    DetatchedCriteria posts = DetachedCriteria.For<Post>("p")
        .SetProjection(Projections.Property("p.IdPost"));        
        .Add(Restrictions.EqProperty("t.IdPost", "p.IdPost"));
    
    DetachedCriteria postMax = DetachedCriteria.For<Post>, "p2")
        .SetProjection(Projections.Max("Date"));
    
    var topics Session.CreateCriteria<Topic>("t")
        .Add(Subqueries.Select(postMax))
        .Add(Subqueries.Exists(posts)).List<Topic>();