2

我很难弄清楚如何执行以下操作。

给定以下类:

public class Post
{
   ...
   public IList<Comment> Comments
   ...    
}

public class Comment
{
    public DateTime CommentDate
    ... Some other properties but no reference to Post...
}

如何编写查询以仅获取按日期降序排列的给定帖子的前 10 条评论?

由于没有来自Commentto的引用Post,我无法查询Comment,我需要查询Post,但我的所有查询似乎都返回了Post,并且我的投影尝试失败了。

我无法添加PostComment(顺便说一句,这实际上不是我的域模型)引用的属性,所以我被卡住了。

我希望我没有遗漏一些明显的东西。

编辑:

如果有从评论到帖子的引用,这会给我我想要的

var query = (from comment in Session.Query<Comment>() orderby comment.CommentDate 
where comment.Post == some Post select comment).Take(10);

但没有,所以我在 Post 上寻找返回 10 条评论列表的等效查询。

如果可以通过 Linq 进行查询,那是我更喜欢的,但使用 QueryOver 会很高兴。

我可能最终会改写我的域模型,以便有那个参考。

4

1 回答 1

0

这是使用 HQL 的解决方案:

var postId = 1;
var hql = "select p.Comments from Post p join p.Comments c where p.PostId = :postId order by c.CommentDate desc";
var result = session.CreateQuery(hql)
    .SetParameter("postId", postId)
    .SetMaxResults(10)
    .List<Comment>();

我无法在 Criteria API 中找到一种方法。

于 2011-08-16T00:08:55.183 回答