LINQ to Entities — Complete Guide
LINQ to Entities — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of LINQ Tutorial on Toolliyo Academy.
On this page
LINQ Tutorial · Lesson 51 of 100
LINQ to Entities
Beginner ✓ → Intermediate ✓ → Advanced → Professional
Advanced · 3 — EF Core & performance · ~18 min read · Module 6: LINQ with EF Core · ShopNest.Analytics
Introduction
This is advanced material: LINQ to Entities. It is what .NET teams use on live products with SQL Server and EF Core. Read the example carefully and try changing one line at a time. LINQ to Entities means writing LINQ against EF Core DbSet
Enable logging in Development: options.LogTo(Console.WriteLine, LogLevel.Information). You will see SELECT ... WHERE ... ORDER BY ... OFFSET ... FETCH — that is your LINQ translated.
When will you use this?
Use EF Core LINQ when data lives in SQL Server and you want type-safe queries in C#.
- Real apps query SQL Server through EF Core — your LINQ becomes SQL at runtime.
- Lazy vs eager loading decides whether one query or ten queries hit the database.
Real-world: Flipkart-style marketplace
Real product: Flipkart-style marketplace (E-commerce). sellers and shoppers rely on product search and order reports every day. On this product, developers use LINQ to Entities to query SQL Server tables through EF Core DbContext. Without it, the team would write longer loops, ship slower features, or pull too much data from SQL Server. The example below is simplified on purpose — production code adds error handling, logging, and tests around the same LINQ pattern.
Production-style code
public async Task<PagedResult<ProductListDto>> SearchProductsAsync(
ProductSearchFilter filter, CancellationToken ct)
{
var q = _context.Products.AsNoTracking().AsQueryable();
if (filter.CategoryId.HasValue)
q = q.Where(p => p.CategoryId == filter.CategoryId);
if (!string.IsNullOrWhiteSpace(filter.Term))
q = q.Where(p => p.Name.Contains(filter.Term));
if (filter.MaxPrice.HasValue)
q = q.Where(p => p.Price <= filter.MaxPrice);
var total = await q.CountAsync(ct);
var items = await q
.OrderBy(p => p.Name)
.Skip((filter.Page - 1) * filter.PageSize)
.Take(filter.PageSize)
.Select(p => new ProductListDto { Id = p.Id, Name = p.Name, Price = p.Price })
.ToListAsync(ct);
return new PagedResult<ProductListDto> { Items = items, Total = total };
}
What happens in production: In Flipkart-style marketplace, getting LINQ to Entities right means sellers and shoppers see correct product search and order reports quickly. That is the difference between a tutorial snippet and software people trust with money and operations data.
Lesson example (start here)
Copy this smaller example first. Once it works, compare it with the real-world code above.
// DbContext is your gateway to the database
public class ShopDbContext : DbContext
{
public DbSet<Product> Products => Set<Product>();
public DbSet<Order> Orders => Set<Order>();
}
// In a service — query is NOT executed until ToListAsync
var query = _context.Products
.Where(p => p.IsPublished && p.StockQty > 0)
.OrderBy(p => p.Name);
var products = await query.ToListAsync();
Line-by-line walkthrough
| Code | What it means |
|---|---|
// DbContext is your gateway to the database | Comment — notes for humans; the compiler ignores it. |
public class ShopDbContext : DbContext | Part of the LINQ to Entities example — read it together with the lines before and after. |
{ | Part of the LINQ to Entities example — read it together with the lines before and after. |
public DbSet<Product> Products => Set<Product>(); | Lambda expression — a short function, e.g. p => p.Price > 100 means "price greater than 100". |
public DbSet<Order> Orders => Set<Order>(); | Lambda expression — a short function, e.g. p => p.Price > 100 means "price greater than 100". |
} | Closes a block started by { or ( above. |
// In a service — query is NOT executed until ToListAsync | Comment — notes for humans; the compiler ignores it. |
var query = _context.Products | EF Core DbContext — gateway to database tables as IQueryable. |
.Where(p => p.IsPublished && p.StockQty > 0) | Lambda expression — a short function, e.g. p => p.Price > 100 means "price greater than 100". |
.OrderBy(p => p.Name); | Lambda expression — a short function, e.g. p => p.Price > 100 means "price greater than 100". |
var products = await query.ToListAsync(); | Runs the query and loads results into a List — query execution happens here. |
How it works (big picture)
- _context.Products is IQueryable.
- Each Where adds to the expression tree.
- CountAsync and ToListAsync send SQL to the database.
- Select projects columns so SQL only fetches what you need.
Do this on your computer
- Create dotnet new webapi -n ShopNestApi.
- Add EF Core SQL Server packages and a Product entity.
- Register DbContext in Program.cs.
- Run one Where + ToListAsync and copy the logged SQL.
- Compare with the in-memory LINQ from lesson 1 — same operators, different provider.
- Read the real-world section and name which part of the app uses this topic.
- Run the example in a console app or LINQPad and confirm the output.
- Change one filter or sort in the example and predict the result before you run it.
Experiments — try changing this
- Change a filter value (price, date, name) and run again — see how results change.
- Remove one operator from the chain, run, and read the error or different output.
- Make the Where condition always false — confirm you get zero results.
- Switch OrderBy to OrderByDescending and confirm sort direction flips.
Remember
DbSet
Common questions
LINQ to Objects vs LINQ to Entities?
Objects = IEnumerable in RAM. Entities = IQueryable via EF Core → SQL.
Does every LINQ operator work on EF?
Most do; some need AsEnumerable() for client evaluation — use sparingly on large data.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!