2014-11-03 178 views
1

實體框架生成SQL查詢的方式會降低網站的運行速度或給cpu帶來很大的壓力。實體框架生成的SQL很慢

我們目前擁有的代碼是

 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 不加快第一段代碼的執行甚至需要一秒鐘來執行所有結果

回答

1

您的查詢看起來很基本我不認爲你應該修補這些。首先,你可以嘗試使用AsNoTracking

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

然後檢查是否有僱員和/或BranchID索引。如果還不滿意,結果可能值partition your database

+0

看起來工作相當不錯,雖然我要去看索引視圖,但我從來沒有這樣做過 – 2014-11-03 09:27:01