【发布时间】:2015-02-21 00:26:16
【问题描述】:
我正在创建我的第一个 MVC5 / EF / LINQ 应用程序,我想在一个视图中显示几个(大约 75 个)“Select Count(*)”查询的结果。目的是在主页“仪表板”上显示来自单个表的不同统计信息,以及来自数据库中同一表的“活动”项目列表。
我已经阅读了关于如何以最佳方式运行选择县查询的不同意见 在 LINQ 中...考虑到我需要在页面上运行多少查询,最有效的方法是什么?
一个示例查询是
select count(*) from TableName WHERE LType="A" AND (LDate BETWEEN 02/10/2015 AND 02/25/2015)
public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.LastNameSortParam = String.IsNullOrEmpty(sortOrder) ? "LastName" : "";
ViewBag.DateSortParam = sortOrder == "Date" ? "LeadDate" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var newLeads = from l in db.WebLeads
where (l.LoanAgent == null || l.LoanAgent == "hb@mwfinc.com")
select l;
if (!String.IsNullOrEmpty(searchString))
{
newLeads = newLeads.Where(l => l.LastName.Contains(searchString)
|| l.FirstName.Contains(searchString));
}
switch (sortOrder)
{
case "Date":
newLeads = newLeads.OrderBy(l => l.LeadDate);
break;
case "LeadDate":
newLeads = newLeads.OrderByDescending(l => l.LeadDate);
break;
case "LastName":
newLeads = newLeads.OrderBy(l => l.LastName);
break;
default:
newLeads = newLeads.OrderByDescending(l => l.LeadDate);
break;
}
int pageSize = 15;
int pageNumber = (page ?? 1);
DateTime minDate = System.DateTime.Today;
DateTime maxDate = System.DateTime.Now;
// Leads to Be Assigned Daily Count
var ctPurchTBA = db.WebLeads.Count(x => (x.LoanType == "Home Purchase" || x.LoanType == "CalPATH Home Purchase")
&& x.LeadDate >= minDate
&& x.LeadDate <= maxDate);
return View(newLeads.ToPagedList(pageNumber, pageSize));
}
'
【问题讨论】:
-
根据表的负载/大小/整体性能考虑,我将采用两种方法: 1. 使用选择计数 (*) 作为子选择的子选择进行选择。您只需将一项传递给 vew 2. 根据表加载/卷上的不同计划加载来自前端的异步请求的总数,以减少 sql 负载。
-
您能否提供方法 1 的示例?不幸的是,我有点新手,所以你的回答有点过头了。
-
既然你用的是EF/Linq,为什么不用你的POCO而不是纯sql。类似 var myPoco = YourDBContext.models 然后你可以使用 mypoco 并根据需要查询它
-
示例:
select tab1.numbers1, tab2.numbers2, tab3.numbers3 from (select count(*) as numbers1 from Table1) as tab1, (select count(*) as numbers2 from Table2) as tab2, (select count(*) as numbers3 from Table3) as tab3但请注意,如果您谈论 75 个表,这对于 SQL 服务器来说是一个性能溢出。我个人会采用异步流程,但这是我个人的看法。
标签: c# asp.net-mvc linq entity-framework