2009-08-10 58 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

相关问题