Roadmap › LINQ — Language Integrated Query › Module: LINQ Internals and EF Core
Lessons in this course (12)
11. LINQ with EF Core: what translates and common pitfalls
Advanced★ Must knowLesson 11 of 12
- Projection with
Selectinto DTOs fetches only needed columns and needs no tracking. - Methods EF can't translate (your own C# methods) cause an exception (EF Core 3.0+ no longer silently evaluates on the client, except in the final
Select). Containson a local list →WHERE Id IN (...)(EF 8+ can send it as a JSON parameter for plan reuse).- N+1: looping over orders and touching
o.Customerwith lazy loading → one query per order. UseIncludeor projection. Count()vsAny(): useAnyAsync()for existence.FirstwithoutOrderBy→ nondeterministic order.- String comparisons follow DB collation (often case-insensitive in SQL Server).
- Use async operators (
ToListAsync,FirstOrDefaultAsync) in web apps.
csharp
var summaries = await db.Customers
.Where(c => c.IsActive)
.Select(c => new CustomerSummary(c.Id, c.Name, c.Orders.Count, c.Orders.Sum(o => (decimal?)o.Total) ?? 0))
.OrderByDescending(s => s.Total)
.Take(10)
.ToListAsync(ct);