例如,假设您有一个具有“评论”(一对多)的实体“帖子”,并且您希望拥有一个包含Post实体和最新评论的视图模型:
PostViewModel {Id,Title,Body,Date,LastComment(type: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)
如何使用QueryOver在nhibernate 3中执行相同的查询?
我尝试使用子查询,但我只能得到一个结果,而不是前10个列表。
答案 0 :(得分: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
};
}
答案 1 :(得分: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>();
我希望它有用。