【发布时间】:2014-12-06 05:54:34
【问题描述】:
Entity 框架生成 SQL 查询的方式正在减慢网站速度或给 cpu 带来很大压力。
我们目前拥有的代码是
var items = (from item in _DatabaseContext.ViewDashboardCounts
where item.EmployeeID == employeeId && item.BranchID == branchId
select item);
由此产生的查询是
SELECT
[Extent1].[EmployeeID] AS [EmployeeID], [Extent1].[C1] AS [C1], [Extent1].[C2] AS [C2],
[Extent1].[C3] AS [C3], [Extent1].[C4] AS [C4], [Extent1].[C5] AS [C5],
[Extent1].[C6] AS [C6], [Extent1].[C7] AS [C7], [Extent1].[C8] AS [C8],
[Extent1].[C9] AS [C9], [Extent1].[BranchID] AS [BranchID]
FROM
(SELECT
[vDashboardCounts].[EmployeeID] AS [EmployeeID],
[vDashboardCounts].[BranchID] AS [BranchID], [vDashboardCounts].[C1] AS [C1],
[vDashboardCounts].[C2] AS [C2], [vDashboardCounts].[C3] AS [C3],
[vDashboardCounts].[C4] AS [C4], [vDashboardCounts].[C5] AS [C5],
[vDashboardCounts].[C6] AS [C6], [vDashboardCounts].[C7] AS [C7],
[vDashboardCounts].[C8] AS [C8], [vDashboardCounts].[C9] AS [C9]
FROM
[dbo].[vDashboardCounts] AS [vDashboardCounts]
)
AS [Extent1]
WHERE ([Extent1].[EmployeeID] = @p__linq__0) AND ([Extent1].[BranchID] = @p__linq__1)
但是这运行了 2 秒,这很慢,但这仍然比我们之前的查询快,但是如果我将“where”移动到内部查询 ([dbo].[vDashboardCounts] AS [vDashboardCounts]),那么执行就会立即执行
这是我们的第一个代码
var items = (from item in _DatabaseContext.ViewDashboardCounts
where item.EmployeeID == employeeId && item.BranchID == branchId
select new List<int?>
{
item.C1,
item.C2,
item.C3,
item.C4,
item.C5,
item.C6,
count,
item.C8,
item.C9
});
执行大约需要 11 秒,但我将此代码更改为
var items = (from item in _DatabaseContext.ViewDashboardCounts
where item.EmployeeID == employeeId && item.BranchID == branchId
select item);
return items.ToList().Select(item => new List<int?>
{
item.C1,
item.C2,
item.C3,
item.C4,
item.C5,
item.C6,
count,
item.C8,
item.C9
}).FirstOrDefault();
我可以做些什么来加快第一段代码的执行,因为视图 vDashboardCounts 甚至不需要一秒钟来执行所有结果
【问题讨论】: