我使用MVC 5& amp;创建了一个新闻Web应用程序。实体框架6.所有者已在1个月内输入了1000多篇文章。应用程序的主页需要很多来自数据库的对象,如
作者,帖子,评论,视频等因此我在我的主页视图和我的主页操作中创建了部分内容,我绑定了一个模型,该模型包含要提供给部分内容的所有数据。
我用glimpse测试了EF 6的性能,并且我还在google页面洞察中运行测试,服务器响应时间越来越长,网站上的文章越来越多。它实际上是大约1200毫秒,这很慢,而且一瞥就是说加载主页时SQL中的连接打开时间是1200毫秒。
所以我需要的是关于代码的一些提示我在主页上的操作是我的操作代码,任何提高性能的提示都非常感谢;
[OutputCache(CacheProfile = "Cache1Hour")]
public async Task<ActionResult> Home()
{
var pageModel = new HomePageModel();
//Eager Load Database Objects
var allPosts = await db.Posts.Include("Authors").Include("Media").Include("PostCategories").ToListAsync();
var allCategories = await db.PostCategories.Include("Posts").ToListAsync();
var allMedia = await db.Media.ToListAsync();
var allAuthors = await db.Authors.Include("Posts").Include("Media").ToListAsync();
var allEstates = await db.Estates.Include("Media").ToListAsync();
var allAdverts = await db.Adverts.Include("Media").ToListAsync();
//Categories
pageModel.PublishedCategories = allCategories.Where(x => !x.IsDeleted && !x.IsOnHeader && !x.IsPrivate).ToList();
//Videos
pageModel.Videos = allMedia.Where(x => !x.IsDeleted && x.IsVideo).OrderByDescending(x => x.CreatedDate).ToList();
//CornerPosts
pageModel.CornerPosts = allPosts.Where(x => !x.IsDeleted && x.IsPublished && x.PostType == 1).OrderByDescending(x => x.PostDate).Take(20).ToList();
//Vitrin Module
pageModel.VitrinCategories = allCategories.Where(x => !x.IsDeleted && x.IsOnHeader).ToList();
//Authors
pageModel.Authors = allAuthors.Where(x => !x.IsDeleted && x.Posts.Count > 0).OrderByDescending(x => x.AuthorName).ToList();
//Slider News
pageModel.SliderNews = allPosts.Where(x => !x.IsDeleted && x.IsPublished && x.PostType == 2 && x.IsOnSlider).OrderByDescending(x => x.PostId).Take(20).ToList();
//Adverts
pageModel.Adverts = allAdverts.Where(x => !x.IsDeleted && x.AdvertArea == 1).OrderByDescending(x => x.CreatedDate).Take(20).ToList();
//Private Category
pageModel.PrivateCategory = allCategories.Where(x => !x.IsDeleted && x.IsPrivate).FirstOrDefault();
//Latest Posts
pageModel.LatestPosts = allPosts.Where(x => !x.IsDeleted && x.IsPublished && x.PostType == 2).OrderByDescending(x => x.PostDate).Take(20).ToList();
//Estates
pageModel.Estates = allEstates.Where(x => !x.IsDeleted && x.IsPublished).OrderBy(x => x.AdDate).Take(10).ToList();
return View(pageModel);
}
由于模式需要不同的帖子dbset上的查询我得到所有帖子然后查询列表而不是一次又一次直接查询数据库。但如果那是一个问题,我也可以改变它。
提前致谢
答案 0 :(得分:0)
您应该限制数据库端返回的记录数。对于20条记录,查询两次DB比获取1000条记录并在内存中过滤要快得多。从DB中获取大量行时,创建EF对象非常昂贵。在DB端,过滤也可以更快 - 如果存在,它可以使用索引。