3

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

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

生成 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]

它似乎正在运行另一个不必要的选择查询。这是使用该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()方法?

4

1 回答 1

2

我怀疑两者之间有任何性能差异,至少对于 sql server。看起来第一个在选择周围有一个额外的包装器。在我已经生成完全相同的计划的数据库上运行类似的查询,所以我可以想象外部选择在执行计划中得到优化。

于 2012-07-05T16:36:20.543 回答