Search code examples
c#sqllinqazure-sql-databasegenerated-sql

Why does Linq ignore my where clause?


I see several StackOverflow questions on this already but not of them seem to match my scenario. I promise I looked.

I have some queries against my database that I'm using linq to do and I can't figure out why the incorrect SQL is being generated. This is happening in several places in my code. I'm hoping we're just falling into some well known gotcha but I can't wrap my head around why Linq seemingly decides my where clause is dumb and shouldn't add it to the generated SQL query.

Why is this?

Example:

var testing = (from i in context.TableName1 where i.Param1 == object1.GuidParam select i).ToList();

The above query returns the following SQL

{SELECT 
    [Extent1].[RecordId] AS [RecordId], 
    [Extent1].[AnotherId] AS [AnotherId], 
    [Extent1].[YetAnotherId] AS [YetAnotherId], 
    [Extent1].[WeLikeIds] AS [WeLikeIds], 
    [Extent1].[WeReallyLikeIds] AS [WeReallyLikeIds]
    FROM [dbo].[SomeTable] AS [Extent1]}

However the following query:

var testing = (from i in context.TableName1 where i.Param1 == object1.GuidParam select i);
var testingToList = testing.ToList();

Generates the following correct SQL

{SELECT 
    [Extent1].[RecordId] AS [RecordId], 
    [Extent1].[AnotherId] AS [AnotherId], 
    [Extent1].[YetAnotherId] AS [YetAnotherId], 
    [Extent1].[WeLikeIds] AS [WeLikeIds], 
    [Extent1].[WeReallyLikeIds] AS [WeReallyLikeIds]
    FROM [dbo].[SomeTable] AS [Extent1]
WHERE [Extent1].[RecordId] = '78e49f5c-0ff8-e311-93f4-00155d514a6d'}

Solution

  • I prefer the lambda notation, and I don't see why this wouldn't work...

    var testing = context.TableName1.Where(i => i.Param1 == object1.GuidParam).ToList();
    

    Cleaner, concise and it should work.