EF Core translates LINQ expressions to SQL. Filter and project in the database—don't fetch entire tables into memory unless intentional.
Common queries
var cheap = await _db.Products
.Where(p => p.Price < 20)
.OrderBy(p => p.Name)
.ToListAsync();
var one = await _db.Products
.FirstOrDefaultAsync(p => p.Id == id);
Projection
var names = await _db.Products
.Select(p => new { p.Id, p.Name })
.ToListAsync();
Project early to reduce columns transferred—especially important for list endpoints.
Important interview questions and answers
- Q: IQueryable vs IEnumerable?
A: IQueryable builds expression trees EF translates to SQL; IEnumerable often means client-side evaluation after ToList. - Q: N+1 problem?
A: Loading related entities in a loop—fix with Include/ThenInclude or projection.
Self-check
- Why call Where before ToListAsync?
- What does FirstOrDefault return when no row matches?
Pitfall: Calling ToList() before Where pulls entire tables into memory—filter and project in LINQ so EF translates to SQL server-side.
Interview prep
- What is N+1 in EF Core?
One query for a list plus one per row for related data—fix with Include/ThenInclude or project in a single Select query.