简体   繁体   English

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

[英]Entity Framework generates inefficient select when using Find()

I am noticing that the Entity Framework is generated some inefficient queries when using the Find() method. 我注意到在使用Find()方法时,实体框架会生成一些低效的查询。 For example here is my C# code. 例如,这是我的C#代码。

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

Generate Find() Query 生成Find()查询

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]

It seems to be running a whole other select query which is unnecessary. 它似乎正在运行一个完整的其他选择查询,这是不必要的。 Here is the output using the SingleOrDefault() method. 这是使用SingleOrDefault()方法的输出。

Generate SingleOrDefault() Query 生成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

Is there a reason why Find() is generating two selects? Find()生成两个选择是否有原因? Should the Find() method be avoided in favor of the SingleOrDefault() method? 是否应该避免使用Find()方法来支持SingleOrDefault()方法?

I doubt there is any performance difference between the two, for sql server at least. 我怀疑两者之间是否存在任何性能差异,至少对于sql server而言。 It looks like the first one just has an extra wrapper around the select. 看起来第一个只是在select周围有一个额外的包装器。 Running a similar query on a database that I have generates the exact same plan, so I would imagine the outer select gets optimized away in the execution plan. 在我拥有的数据库上运行类似的查询会生成完全相同的计划,因此我认为外部选择在执行计划中得到优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM