我的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);
}