处理“N + 1”+计数问题的正确方法是什么?

时间:2011-07-09 09:44:13

标签: entity-framework entity-framework-4.1 dbcontext

如下所示:

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

任何人都知道正确的方法吗?

谢谢!

2 个答案:

答案 0 :(得分: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实体。

答案 1 :(得分: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)

Etc等

相关问题