带有.AsEnumerable()的实体框架6.0性能问题,带有glimpse asp.net screenshot

时间:2015-11-24 18:05:08

标签: asp.net asp.net-mvc linq-to-entities entity-framework-6 asp.net-identity

我正在尝试查询数据库,但它在登录时使用了我的性能问题               signinmanager.passwordsigninasync() 在初始登录请求期间,方法需要3秒。 在从数据库中获取数据时,查询

    var allposts = _context.Posts
            .Where(t => t.PostAuthor.UserName == userName && t.Archived == isArchived) //.ToList();
                               .Select(e => new
                               {
                                   e,//for later projection
                                   e.Comments,//cache Comments
                                   Sender = e.Comments.Select(m => m.Sender),//cache Comments
                                   Receiver = e.Comments.Select(m => m.Receiver),//cache Comments
                                   //cache filtered Attachments
                                   Attachments = e.Attachments.Where(a => a.Owner is Teacher),
                                   e.PersonPosts,
                                   e.PostAuthor, //cache PostAuthor
                                   e.PostSfClass,

                               })
                               .AsEnumerable()
                               .Select(e => e.e).ToList();

需要8秒才能获取数据。 还附上了登录页面加载的一瞥截图,以供参考。请帮忙。

2 个答案:

答案 0 :(得分:0)

不要注意开发中的加载时间。您从Glimpse等工具获得的信息仅适用于您网站上的其他数据。如果一个页面加载到30秒加载,而大多数只需要1-10秒,那么你就知道该页面上有什么东西要看。但是,通常调试您的站点会导致所有内容加载速度变慢,并且根据您的计算机的规格以及您在该计算机上运行的其他内容,它可能会慢得多。

如果您需要有关页面加载性能的有意义的统计信息,则无法替代将您的站点发布到将要部署到的服务器的服务器,包括您将使用的任何数据库服务器的设置。然后,您可以对太慢的事情进行分析和决策。在开发过程中,在本地计算机上,您无法说明网站的最终性能。

那说,小心懒惰加载。正如您现在所做的那样,您应该没问题,因为Select应该包含在查询中,并且所有这些关系都将被连接起来。但是,在致电.ToList之前,您已Select注释掉了。如果您先调用ToList,那么当您到达Select时,所有这些关系都会发出自己的查询,从而为每个查询生成N + 1查询方案。为了安全起见,最好为您打算访问的每个关系调用Include,这样您就会知道所有内容都会立即被查询,而不是依赖操作的机会或顺序来确定查询。

答案 1 :(得分:0)

通常,你不想加载部分类,但这应该做你想要的,我想。通常情况下,我只会包含整个附件集合,并且只使用我需要的内容,但如果查询过大,则必须执行您必须执行的操作。

allposts = _context.Posts
  .Where(t => t.PostAuthor.UserName == userName && t.Archived == isArchived)
  .Include(p=>p.Comments)
  .Include(p=>p.Comments.Select(m=>m.Sender))
  .Include(p=>p.Comments.Select(c=>c.Receiver))
  .Include(p=>p.PersonPosts)
  .Include(p=>p.PostAuthor)
  .Include(p=>p.PostSfClass);

//preload teacher attachments
allposts.SelectMany(p=>p.Attachments.Where(a=>a.Owner is Teacher)).Load();
相关问题