我在我的数据库上运行以下查询,它会生成一个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