【问题标题】:Entity Framework generated SQL is slow实体框架生成的 SQL 很慢
【发布时间】: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 甚至不需要一秒钟来执行所有结果

【问题讨论】:

    标签: entity-framework-5


    【解决方案1】:

    您的查询看起来很基本,我认为您不应该修补它。首先你可以尝试使用AsNoTracking:

        _DatabaseContext.ViewDashboardCounts.AsNoTracking()
    .Where(item => item.EmployeeID == employeeId && item.BranchID == branchId).ToList()
    

    然后检查您是否有 EmployeeID 和/或 BranchID 的索引。如果对结果仍然不满意可能值得partition your database

    【讨论】:

    • 似乎工作得很好,虽然我打算看看索引视图,但我以前从未这样做过
    猜你喜欢
    • 2017-07-28
    • 2012-10-23
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多