NHibernate 查询获取给定 List 属性的 top(x) 实体

发布于 2024-11-29 14:08:19 字数 937 浏览 5 评论 0原文

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

给定以下类:

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

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

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

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

我无法添加从 Comment 引用 Post 的属性(顺便说一句,这实际上不是我的域模型),所以我陷入了困境。

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

编辑:

如果有从评论到帖子的引用

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

,但没有,这会给我我想要的东西,所以我正在寻找返回 10 条评论列表的帖子上的等效查询。

如果可以通过 Linq 进行查询,这就是我想要的,但使用 QueryOver 会很高兴。

我可能最终会重新设计我的领域模型,以便有该参考。

I'm having difficulties figuring out how to do the following.

Given the following classes:

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

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

How can I write a query to get only the first 10 comments for a given post ordered by date descending?

As there is no reference from Comment to Post, I can't query on Comment, I need to query on Post, but all my queries seem to return Post, and my attempts at projection have failed.

I can't add a property referencing Post from Comment (BTW that isn't actually my domain model), so I am stuck.

I hope I'm not missing something obvious.

Edit:

This would give me what I want if there was a reference from Comment to Post

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

but there is not, so I'm looking for the equivalent query on Post that returns a List of 10 Comments.

If the query is possible via Linq, that's what I'd prefer, but would be happy enough using QueryOver.

I might just end up reworking my Domain Model instead, so that there is that reference.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

揪着可爱 2024-12-06 14:08:19

这是使用 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 中执行此操作的方法。

Here's a solution using 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>();

I couldn't figure out a way to do it in the Criteria API.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文