Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 791
Stefan Bossbaly Avatar asked Jun 06 '26 04:06

Stefan Bossbaly


1 Answers

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.

like image 89
Ted Elliott Avatar answered Jun 08 '26 23:06

Ted Elliott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!