Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Entity Framework 6 generate complex SQL queries for simple lookups?

I have this LINQ query

dbContext.Customers.Where(c => c.AssetTag == assetTag).Count();

or

(from c in dbContext.Customers
 where c.AssetTag == assetTag
 select c).Count();

The generated SQL is

SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    COUNT(1) AS [A1]
    FROM [dbo].[Customer] AS [Extent1]
    WHERE (([Extent1].[AssetTag] = @p__linq__0) AND ( NOT ([Extent1].[AssetTag] IS NULL    OR @p__linq__0 IS NULL))) OR (([Extent1].[AssetTag] IS NULL) AND (@p__linq__0 IS NULL))
)  AS [GroupBy1]

So why does LINQ generate such complex SQL for a simple where statement?

like image 241
Vinod Shinde Avatar asked Nov 20 '13 21:11

Vinod Shinde


1 Answers

in C# string equivalency, null == null evaluates to True. null == null in the database evaluates to False. The script is verifying that either both the column value and the parameter are null, or that both are not null and they have the same string value.

WHERE 
    (
        -- neither the column nor the paramter are null and
        -- the column and the parameter have the same string value
        ([Extent1].[AssetTag] = @p__linq__0) AND 
        ( NOT ([Extent1].[AssetTag] IS NULL    OR @p__linq__0 IS NULL))
    ) 
    OR 
    (
        -- both the column value and the parameter are null
        ([Extent1].[AssetTag] IS NULL) AND 
        (@p__linq__0 IS NULL)
    )
like image 182
Moho Avatar answered Oct 04 '22 03:10

Moho