2011-09-01 57 views
1

例如,假設您有一個實體'Post'具有'Comments'(一對多),並且您希望使用Post實體和最新的視圖模型評論:QueryOver對JoinAlias的幫助和子查詢中的過濾器

PostViewModel {ID,標題,正文,日期,LastComment(類型:CommentEntity)}

我可以在普通的SQL就像這樣:

SELECT TOP 10 * 
FROM Posts 
INNER JOIN Comments ON Comments.PostID = Posts.PostID 
WHERE Comments.[Date] = 
(SELECT MAX(c.[Date]) FROM Comments AS c WHERE c.PostID = Posts.PostID GROUP BY c.PostID) 

我怎麼能這樣做相同的查詢在nhibernate 3中使用QueryOver?

我試過子查詢,但我只能得到一個結果,而不是前10名單。

回答

0

您可以嘗試使用collection filters以獲取最新的發表評論:

var posts = session.CreateCriteria<Post>() 
    .SetMaxResults(10) 
    .List<Post>(); 

foreach (Post post in posts) { 

    Comment lastComment = session.CreateFilter(post.Comments, 
               "order by this.Date desc") 
     .SetFirstResult(0) 
     .SetMaxResults(1) 
     .List() 
     .FirstOrDefault(); 

    new PostViewModel { 
     Id = post.Id, 
     Title = post.Title, 
     LastComment = lastComment 
    }; 
} 
0

我試圖解決你的問題,但我不能在此刻

Comments coms = null; 
Post pst = null; 

var qOverInclude = QueryOver.Of<Comments>(() => coms) 
    .Select(Projections.Max(coms.Date) 
     , Projections.Group(()=>coms.PostID)); 

var qOver = _HibSession.QueryOver<Post>(() => pst) 
     .JoinAlias(() => pst.Comments,() => coms, JoinType.LeftOuterJoin) 
     .WithSubquery.WhereProperty(() => coms.Date).In(qOverInclude) 
     .Take(10) 
     .List<Post>(); 
試試我的代碼

我希望這是有幫助的。