实体框架:添加表后会导致查询速度慢的原因是什么?

时间:2014-08-22 22:03:37

标签: c# .net entity-framework sqlite

我有一个连接到SQLite数据库的实体框架5项目。 我做了模型第一种方法,我能够在大约3秒钟内从Table_A查询30,000条记录。

现在我所做的只是另一个Table_B,它对Table_A中的父记录有0到1个引用。在Table_A上运行SAME查询需要3分钟以上。 Table_B中包含ZERO记录。

还值得注意的是,EDMX将导航属性添加到Table_A和Table_B。但是它只将外键列添加到Table_B。什么会导致实体框架减慢那么多?当我将我的更改恢复为旧模型时,它会快速运行。

更新

作为参考,查询是sq查询的标准linq。

var matches = Table_A.Where(it => it.UserName == "Waldo" || it.TimeStamp < oneMonthAgo);

1 个答案:

答案 0 :(得分:2)

我刚刚运行ToTraceString()来查找这个人在他的回答here中建议的生成的SQL查询:

结果实体框架试图“聪明”,期望我会使用来自子记录的数据。这实际上非常酷!只是减慢我的查询速度,所以我可能会找到更快的解决方法。

请注意,此查询在LINQ语法中相同。这只是我在EDMX图中添加另一个表时生成的基础SQL。

以下是FAST查询:(缩写为清晰)

SELECT *

FROM   [Table_A] AS [Extent1]
INNER JOIN  (SELECT 
[Extent2].[OID] AS [K1], 
[Extent2].[C_Column1] AS [K2], 
Max([Extent2].[Id]) AS [A1]
FROM [Table_A] AS [Extent2]
GROUP BY [Extent2].[OID], [Extent2].[C_Column1] ) AS [GroupBy1] ON [Extent1].[Id] = 
[GroupBy1].[A1]
INNER JOIN [OtherExistingTable] AS [Extent3] ON [Extent1].[C_Column1] = [Extent3].[Id]

添加 Table_B 后,这就是生成的新查询,这会让事情变得更慢。

SELECT *
FROM    [Table_A] AS [Extent1]
LEFT OUTER JOIN [Table_B] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Table_B_ForeignKey_To_Table_A]
INNER JOIN  (SELECT 
    [Join2].[K1] AS [K1], 
    [Join2].[K2] AS [K2], 
    Max([Join2].[A1]) AS [A1]
    FROM ( SELECT 
        [Extent3].[OID] AS [K1], 
        [Extent3].[C_Column1] AS [K2], 
        [Extent3].[Id] AS [A1]          
        FROM  [Table_A] AS [Extent3]            
        LEFT OUTER JOIN [Table_B] AS [Extent4] ON [Extent3].[Id] = [Extent4].[Table_B_ForeignKey_To_Table_A]
    )  AS [Join2]
    GROUP BY [K1], [K2] ) AS [GroupBy1] ON [Extent1].[Id] = [GroupBy1].[A1]
INNER JOIN [FeatureServices] AS [Extent5] ON [Extent1].[C_Column1] = [Extent5].[Id]