2

假设模型如下:

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 问题。

有人知道正确的方法吗?

谢谢!

4

2 回答 2

2

您的表示层/视图模型需要这个吗?在这种情况下,创建专门的 ViewModel

public class PostListView 
{
    public Post Post { get; set; }
    public int CommentsCount { get; set; }
}

并使用投影查询:

var data = context.Posts
                  .Select(p => new PostListView
                      {
                          Post = p,
                          CommentsCount = p.Comments.Count()
                      });

你完成了。如果您需要它,您可以将其展平PostListView,使其包含Post的属性而不是Post实体。

于 2011-07-09T11:24:51.103 回答
0

像这样的东西怎么样:

public class PostView
{
    public String PostName { get; set; }
    public Int32 PostCount { get; set; }
}

public static IEnumerable<PostView> GetPosts()
    {
        var context = new PostsEntities();

        IQueryable<PostView> query = from posts in context.Posts
                                     select new PostView
                                                {
                                                    PostName = posts.Title,
                                                    PostCount = posts.PostComments.Count()
                                                };

        return query;
    }

然后使用这样的东西:

foreach (PostView post in GetPosts())
        {
            Console.WriteLine(String.Format("Post Name: {0}, Post Count: {1}", post.PostName, post.PostCount));
        }

应该这样显示列表:

  • 职位名称 (12)
  • 职位名称 (1)

等等等等

于 2011-07-09T12:16:38.310 回答