我的 MVC 4 应用程序运行速度太慢时遇到问题。我安装了 Glimpse 来分析应用程序。我想我已经找到了问题的一部分:我的许多 EF 查询似乎运行了两次!这是我的 HomeController 正在拉一些警报:
[HttpGet]
public virtual ActionResult Index()
{
var reportStart = DateTime.Today;
var reportEnd = DateTime.Today.AddMonths(1);
var query = _tameUow.Alerts
.FindBy(a => a.ApprovalStatusId == (int)AlertApprovalStatusCodes.Approved &&
(a.ScheduledStartDateTime >= reportStart &&
a.ScheduledStartDateTime <= reportEnd), a => a.SubmittedBy, a => a.ApprovalManager, a => a.ApprovalStatus);
var model = ListAlertsViewModelBuilder.Build(query, null, false, false, false, false);
model.RequiredViewData = new RequiredViewDataModel("Upcoming Alerts", "These are the upcoming active alerts for the next month.", "Home");
return View(model);
}
但是当我瞥见 SQL 选项卡时,它显示了两次查询!起初我以为这只是一个错误,同一个查询被显示了两次,但它们的执行时间不同,所以我认为查询实际上是运行了两次!此外,黄色的小感叹号显示为警告。我认为这是在警告我这是一个重复的查询...
http://i.imgur.com/jizQwKz.png 这里发生了什么?我在我测试过的所有页面上都看到了这一点,我选择了这个作为示例,因为它是最简单的。我尝试在查询上设置断点,它只被命中一次。
这是VMBuilder:
public static class ListAlertsViewModelBuilder
{
public static ListAlertsViewModel Build
(IQueryable<Alert> query
, string curUserExtId
, bool showSubmittedDateTime
, bool showStatus
, bool showActions
, bool showOwners)
{
var model = new ListAlertsViewModel();
var alerts = query.Select(a => new AlertDetailsViewModel() {
AlertId = (int)a.AlertId,
ApprovalManager = a.ApprovalManager,
ApprovalManagerExtId = a.ApprovalManagerExtId,
ApprovalStatus = a.ApprovalStatus,
ApprovalStatusId = (int)a.ApprovalStatusId,
Building = a.Building,
Cause = a.Cause,
//Comments = a.Comments,
Impact = a.Impact,
ScheduledEndDateTime = a.ScheduledEndDateTime,
ScheduledStartDateTime = a.ScheduledStartDateTime,
Service = a.Service,
SubmittedBy = a.SubmittedBy,
SubmittedByExtId = a.SubmittedByExtId,
SubmittedDateTime = a.SubmittedDateTime,
CurrentUserExtId = curUserExtId
});
model.ListAlerts = alerts;
model.ShowSubmittedDateTime = showSubmittedDateTime;
model.ShowStatus = showStatus;
model.ShowActions = showActions;
model.ShowOwners = showOwners;
return model;
}
}
这是我在存储库中使用的 FindBy 方法:
public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = this.Context.Set<T>();
foreach (var include in includeProperties)
{
query.Include(include);
}
return query.Where(predicate);
}