我在我的數據庫上運行以下查詢,它會生成一個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服務器本身需要更改一些設置?
我剛剛發現了這個,並且回到這裏來提交我自己的答案。本文對學習編譯查詢有很大幫助: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