I am noticing that the Entity Framework is generated some inefficient queries when using the Find()
method. For example here is my C# code.
Model model = unit.Repository.DbSet.Find(model.ID);
Generate Find() Query
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.
Generate SingleOrDefault() Query
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? Should the Find()
method be avoided in favor of the SingleOrDefault()
method?
I doubt there is any performance difference between the two, for sql server at least. It looks like the first one just has an extra wrapper around the 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.