使用Find()时实体框架生成低效选择

时间:2012-07-05 15:30:25

标签: c# sql-server entity-framework

我注意到在使用Find()方法时,实体框架会生成一些低效的查询。例如,这是我的C#代码。

Model model = unit.Repository.DbSet.Find(model.ID);

生成查询()查询

DECLARE @p0 int = 1

SELECT 
[Limit1].[ID] AS [ID], 
[Limit1].[UserID] AS [UserID], 
[Limit1].[Started] AS [Started], 
[Limit1].[Updated] AS [Updated], 
[Limit1].[Completed] AS [Completed]
FROM ( SELECT TOP (2) 
        [Extent1].[ID] AS [ID], 
        [Extent1].[UserID] AS [UserID], 
        [Extent1].[Started] AS [Started], 
        [Extent1].[Updated] AS [Updated], 
        [Extent1].[Completed] AS [Completed]
        FROM [dbo].[Table] AS [Extent1]
        WHERE [Extent1].[ID] = @p0
)  AS [Limit1]

它似乎正在运行一个不必要的整个其他选择查询。以下是使用SingleOrDefault()方法的输出。

生成SingleOrDefault()查询

DECLARE @p__linq__0 int = 1

SELECT TOP (2) 
[Extent1].[ID] AS [ID], 
[Extent1].[UserID] AS [UserID], 
[Extent1].[Started] AS [Started], 
[Extent1].[Updated] AS [Updated], 
[Extent1].[Completed] AS [Completed]
FROM [dbo].[Table] AS [Extent1]
WHERE [Extent1].[ID] = @p__linq__0

Find()产生两个选择是否有原因?是否应该采用Find()方法来支持SingleOrDefault()方法?

1 个答案:

答案 0 :(得分:2)

我怀疑这两者之间的性能差异至少对于sql server而言。看起来第一个只是在select周围有一个额外的包装器。在我拥有的数据库上运行类似的查询生成完全相同的计划,因此我认为外部选择在执行计划中得到优化。