Nhibernate 子查询中JoinAlias和filter的QueryOver帮助
例如,假设您有一个具有“注释”(一对多)的实体“Post”,并且您希望有一个包含Post实体和最新注释的视图模型: PostViewModel{Id、标题、正文、日期、LastComment(类型:CommentEntity)} 我可以在普通sql中执行此操作,如:Nhibernate 子查询中JoinAlias和filter的QueryOver帮助,nhibernate,join,max,queryover,Nhibernate,Join,Max,Queryover,例如,假设您有一个具有“注释”(一对多)的实体“Post”,并且您希望有一个包含Post实体和最新注释的视图模型: PostViewModel{Id、标题、正文、日期、LastComment(类型:CommentEntity)} 我可以在普通sql中执行此操作,如: SELECT TOP 10 * FROM Posts INNER JOIN Comments ON Comments.PostID = Posts.PostID WHERE Comments.[Date] = (SELECT
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名列表。您可以尝试使用获取帖子的最新评论:
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
};
}
var posts=session.CreateCriteria()
.SetMaxResults(10)
.List();
foreach(以职位为单位的职位){
Comment lastComment=session.CreateFilter(post.Comments,
“在此日期前订购”
.SetFirstResult(0)
.SetMaxResults(1)
.List()
.FirstOrDefault();
新PostViewModel{
Id=post.Id,
Title=post.Title,
LastComment=LastComment
};
}
我已尝试解决您的问题,但目前无法尝试我的代码
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>();
注释coms=null;
pst后=空;
变量qOverInclude=查询(()=>通信量)
.选择(投影最大值(通信日期)
组(()=>coms.PostID));
变量qOver=\u HibSession.QueryOver(()=>pst)
.JoinAlias(()=>pst.Comments,()=>coms,JoinType.LeftOuterJoin)
.WithSubquery.WhereProperty(()=>coms.Date).In(qOverInclude)
.Take(10)
.List();
我希望这会有帮助