2009-08-10 52 views
0

我在我的數據庫上運行以下查詢,它會生成一個sql查詢我知道返回0結果,並且在sql管理工作室中運行需要不到一秒的時間才能返回。爲什麼在linqtosql中獲取空結果集需要這麼長時間?

var query = (from item in db.Table 
      where item.Field == FieldValue // Field is not the primary key but is indexed 
      from other in item.Associated_Table 
      select other.Table); 
List<Table> result = query.ToList(); 

Associated_Table是一個連接表,它將表中的項與表中的其他項關聯起來。生成的查詢如下所示:

declare @p0 as int 

SELECT 
    [t2].[ItemCategoryID], 
    [t2].[InventoryItemID], 
    [t2].[SiteID], 
    [t2].[ItemDescription], 
    [t2].[AverageMonthlyUsage], 
    [t2].[ReorderLevel], 
    [t2].[ReorderQuantity], 
    [t2].[OtherItemDetails], 
    [t2].[Price] AS [IntPrice], 
    [t2].[Ordinal], 
    [t2].[IsBase] AS [IntIsBase], 
    [t2].[Units], 
    [t2].[ProfitCenterID] AS [IntProfitCenterID], 
    [t2].[AccountID], 
    [t2].[PLU] AS [IntPLU], 
    [t2].[BarCode], 
    [t2].[DisplayName], 
    [t2].[ExtraServiceAmount] AS [IntExtraServiceAmount], 
    [t2].[IsSearchable], 
    [t2].[Terminated], 
    [t2].[PdxServiceKey], 
    [t2].[IsOpenPrice], 
    [t2].[ItemPromotionCategoryID] 
FROM 
    [dbo].[Inventory.Item] AS [t0] 
CROSS JOIN 
    [dbo].[Inventory.ItemExtraAssignment] AS [t1] 
INNER JOIN 
    [dbo].[Inventory.Item] AS [t2] 
     ON [t2].[InventoryItemID] = [t1].[ExtraInventoryItemID] 
WHERE 
    ([t0].[PLU] = @p0) AND 
    ([t1].[InventoryItemID] = [t0].[InventoryItemID]) 

在management studio中,此查詢在一秒之內運行並返回0結果。爲什麼需要2秒鐘來執行運行相同查詢的2行c#?我意識到LinqToSql會花費一些開銷來解析對象,但由於沒有對象被返回,它不應該有任何工作要做。

是否有一些優化我失蹤;或者可能在dbml或SQL服務器本身需要更改一些設置?

回答

1

的LINQ必須翻譯在運行時表達式樹。通常它會將表達式樹翻譯爲查詢評估的一部分,但對於許多查詢,您可以使用CompiledQuery單獨執行此操作。

//do this once 
Func<CustomDataContext, int, List<Table>> queryFunc = 
System.Data.Linq.CompiledQuery.Compile<CustomDataAccess, int, List<Table>> 
((dc, i) => 
    from item in dc.Table 
    where item.Field == i 
    from other in item.Associated_Table 
    select other.Table).ToList() 
); 
    //time this 
List<Table> result = queryFunc(db, FieldValue); 
+0

我剛剛發現了這個,並且回到這裏來提交我自己的答案。本文對學習編譯查詢有很大幫助:http://msmvps.com/blogs/omar/archive/2008/10/27/solving-common-problems-with-compiled-queries-in-linq-to-sql - 用於高需求爲ASP淨websites.aspx – Mykroft 2009-08-10 17:14:45

0

第二次運行查詢是否還需要2秒? LINQ to SQL可能需要相當長的時間才能加載它的依賴關係,並且第一次執行各種初始化操作,但之後會很快。

此外,我建議你看一下SQL Server日誌,看看從LINQ運行時查詢在數據庫中花了多長時間。

+0

它每次需要1.6到1.8秒的時間。我得看看服務器日誌。 – Mykroft 2009-08-10 14:53:42

+0

根據sql服務器分析器,該查詢需要不到一秒的時間來處理。 – Mykroft 2009-08-10 15:11:36

1

您正在描述的行爲表示由於過期統計信息,傾斜索引或不正確的參數嗅探而導致不再適合的緩存查詢計劃。

嘗試重建相關表上的索引,或者至少更新您的統計信息。

[SSMS發射前同步碼,每次強制重新編譯]

+0

重建索引並更新統計信息似乎不起作用。 – Mykroft 2009-08-10 15:18:30

+0

@Mykroft:你能捕捉緩慢和普通查詢的執行計劃嗎? – 2009-08-10 15:33:38

相關問題