假设模型如下:
class public Post
{
public int Id {get; set;}
public virtual ICollection<Comment> Comments {get;set;}
}
在帖子/索引页面中,我想显示一个帖子列表,其中包含每个帖子的评论数(不是所有帖子的评论总数)。
1:如果我使用
context.Posts.Include("Comments")
它将加载所有相关评论的整个实体,实际上我只需要评论计数。
2:如果我一个一个地计算每个帖子的数量:
var commentCount = context.Entry(post)
.Collection(p => p.Comments)
.Query()
.Count();
这是一个 N+1 问题。
有人知道正确的方法吗?
谢谢!