开发者

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

开发者 https://www.devze.com 2023-03-07 00:03 出处:网络
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 lates

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) A开发者_运维技巧S Date FROM Posts GROUP BY IdTopic) AS MaxDates WHERE MaxDates.IdTopic = Posts.IdTopic AND MaxDates.Date = Posts.Date

Tks[]

Patrick Coelho


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号