【发布时间】:2014-02-07 15:14:58
【问题描述】:
我是 C#、ASP.NET MVC 和 SQL Server 的新手,但我已经让这段代码工作了
DateTime startDate = DateTime.Parse(start);
DateTime endDate = DateTime.Parse(end);
ViewData["TotalDuringPeriod"] = db.AlcoholForms.Count(x => x.CreatedDate >= startDate && x.CreatedDate <= endDate);
ViewData["TotalUniqueClientsDuringPeriod"] = db.AlcoholForms.Where(x => x.CreatedDate >= startDate && x.CreatedDate <= endDate).Select(x => x.ClientId).Distinct().Count();
ViewData["TotalGateNew"] = db.AlcoholForms.Count(x => x.ReferredTo == "Gate" && x.Reengagement == false && (x.CreatedDate >= startDate && x.CreatedDate <= endDate));
ViewData["TotalGateReengagment"] = db.AlcoholForms.Count(x => x.ReferredTo == "Gate" && x.Reengagement && (x.CreatedDate >= startDate && x.CreatedDate <= endDate));
ViewData["TotalSwitchNew"] = db.AlcoholForms.Count(x => x.ReferredTo == "Switch" && x.Reengagement == false && (x.CreatedDate >= startDate && x.CreatedDate <= endDate));
ViewData["TotalSwitchReengagement"] = db.AlcoholForms.Count(x => x.ReferredTo == "Switch" && x.Reengagement && (x.CreatedDate >= startDate && x.CreatedDate <= endDate));
List<ReportAlcoholReferals> reportData = db.AlcoholForms.Where(x => x.Referral && (x.CreatedDate >= startDate && x.CreatedDate <= endDate)).Select(x => new ReportAlcoholReferals()
{
FirstName = x.Client.FirstName,
LastName = x.Client.LastName,
Date = x.CreatedDate,
ClientId = x.ClientId,
AlcoholForm = x
}).OrderBy(x => x.AlcoholForm.ReferredTo).ToList();
return View(reportData);
现在它可以工作了,但我要访问数据库 7 次?有没有更好的方法来做到这一点? 有多大的性能问题
【问题讨论】:
-
听起来您需要一个 List
,这样您就可以查询一次,然后在所有后续 LINQ 查询中利用该对象。
标签: sql-server database-administration c# linq