Domdhi logoDOMDHI.OS
BACK_TO_COURSE

From SQL to Entity Framework

The Same Query as LINQ

EF Writes SQL. You Still Judge the SQL.

Entity Framework Core lets C# code ask for data without writing SQL. You write LINQ, EF translates it, the database runs the translation. So everything from Module 1 still applies. The bugs didn't leave. They got a coat.

A revenue by region report, as LINQ:

var from = new DateTime(2025, 3, 1);
var to   = new DateTime(2025, 4, 1);

var query = db.Orders
    .Where(o => o.Status == "Shipped"
             && o.OrderDate >= from && o.OrderDate < to)
    .SelectMany(o => o.Lines, (o, l) => new
    {
        o.Customer.Region,
        o.OrderId,
        LineTotal = l.Quantity * l.UnitPrice
    })
    .GroupBy(x => x.Region)
    .OrderBy(g => g.Key)
    .Select(g => new RegionRevenue(
        g.Key,
        g.Select(x => x.OrderId).Distinct().Count(),
        g.Sum(x => x.LineTotal)));

RegionRevenue is a plain record: public record RegionRevenue(string Region, int Orders, decimal Revenue);

Ask EF what it will really send, before running anything:

Console.WriteLine(query.ToQueryString());
SELECT [c].[Region], COUNT(DISTINCT ([o].[OrderId])),
    COALESCE(SUM(CAST([o0].[Quantity] AS decimal(10,2))
        * [o0].[UnitPrice]), 0.0)
FROM [Orders] AS [o]
INNER JOIN [OrderLines] AS [o0] ON [o].[OrderId] = [o0].[OrderId]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[CustomerId]
WHERE [o].[Status] = 'Shipped'
    AND [o].[OrderDate] >= @from AND [o].[OrderDate] < @to
GROUP BY [c].[Region]
ORDER BY [c].[Region]

Ugly names, good query. ToQueryString() is your best tool in EF. Use it on anything that matters.

SQL LINQ
WHERE .Where(...)
the columns in SELECT .Select(o => new { ... })
JOIN use the link: o.Customer.Name
LEFT JOIN .LeftJoin(...) (EF Core 10)
EXISTS .Any(...)
TOP (10) .Take(10)

Where the Translation Bites

The list that came too early. Everything before ToListAsync() runs in the database. Everything after runs in your app's memory.

// WRONG: loads all 500,000 orders to keep 52
var all  = await db.Orders.ToListAsync();
var mine = all.Where(o => o.CustomerId == 42).ToList();

// RIGHT: the database does the filtering
var orders = await db.Orders
    .Where(o => o.CustomerId == 42)
    .Select(o => new { o.OrderId, o.OrderDate, o.Status })
    .ToListAsync();

The function in disguise. o.OrderDate.Year == 2025 becomes DATEPART(year, [o].[OrderDate]) = 2025. That's the slow pattern from Module 1. Use a date range in LINQ too.

The wrong text type. EF assumes string means Unicode with no length limit: nvarchar(max). If your column is varchar, tell EF, or its lookups get the type mismatch from Module 1, which means a scan under a SQL_ collation like the one tested there:

modelBuilder.Entity<Customer>()
    .Property(c => c.Email)
    .HasMaxLength(200)
    .IsUnicode(false);

NULL changes its mind. In SQL, Notes <> 'x' skips NULLs. In LINQ, o.Notes != "x" keeps them: EF adds OR [Notes] IS NULL so it acts like C#. Same-looking filter, different rows. Watch for it when AI ports a query from one to the other.

TIP

Only reading? Add .AsNoTracking() when you load whole entities. EF skips keeping a second copy of each row to watch for changes. Queries that select plain values aren't tracked in the first place.

QUIZ

What's the fastest way to see whether a LINQ query is any good?

Sign in to track lesson progress and earn a certificate.SIGN IN TO SAVE PROGRESS