Tutorials Entity Framework Core Tutorial
Dynamic LINQ with EF Core
Dynamic LINQ with EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 40 of 100
Dynamic LINQ with EF Core
Beginner ✓ → Intermediate → Advanced → Professional
Intermediate · 2 — Data & queries · ~6 min · Module 4: LINQ
What is this?
Dynamic LINQ builds predicates and sorts at runtime from user input — using expression trees, PredicateBuilder, or System.Linq.Dynamic.Core with strict whitelisting.
Why should you care?
ShopNest admin grid lets users pick sort column and filters — dynamic LINQ composes safe queries without twenty nearly duplicate methods.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
var query = _context.Products.AsQueryable();
if (!string.IsNullOrEmpty(sortBy) && AllowedSorts.Contains(sortBy))
query = sortBy switch
{
"price" => query.OrderBy(p => p.Price),
"name" => query.OrderBy(p => p.Name),
_ => query.OrderBy(p => p.Id)
};
if (brandId.HasValue)
query = query.Where(p => p.BrandId == brandId);
return await query.ToListAsync();
What happened?
- Whitelist AllowedSorts prevents arbitrary property access.
- Switch maps user sort tokens to typed OrderBy — EF still translates to SQL.
Practice next
- Never pass raw user strings to Dynamic LINQ without whitelist.
- Build filters with optional Where clauses on IQueryable.
- Consider System.Linq.Dynamic.Core only with reviewed field maps.
- Add descending flag toggling OrderBy vs OrderByDescending.
- Combine PredicateBuilder for optional min/max price range.
Remember
Dynamic queries still use IQueryable composition. Whitelist sort and filter fields. Prefer typed switches over raw dynamic strings.
ShopNest admin grid
Seller portal grid whitelists sort by price, name, stock for catalog management.
Outcome: Flexible UX without opening SQL injection via sort parameters.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!