我使用 MVC 5 和 Entity Framework 6 构建了一个新闻 Web 应用程序。所有者在1个月内已经输入了1000+文章。应用程序的主页需要来自数据库的大量对象,例如,
作者,帖子,评论,视频等所以我在我的主页视图中创建了部件,在我的主页操作中,我绑定了一个模型,该模型包含要提供给部件的所有数据。
我使用 glimpse 来测试 EF 6 性能,我还在谷歌页面见解上运行了测试,服务器响应时间随着网站上文章数量的增加而增加。它实际上是大约 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);
}
由于模式需要不同的查询帖子数据库集,我正在获取所有帖子,然后查询列表,而不是一次又一次地直接查询数据库。但如果这是一个问题,我也可以改变它。
提前致谢
您应该限制数据库端返回的记录数。查询 20 条记录的数据库的两倍比获取 1000 条记录并在内存中过滤要快得多。从数据库提取大量行时,创建 EF 对象的开销非常大。此外,数据库端的过滤速度更快 - 如果存在,它可以使用索引。