Tutorials Design Patterns in C#
Specification Pattern — Enterprise Query Design
Specification Pattern — Enterprise Query Design: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 37 of 69
Specification Pattern — Enterprise Query Design
GoF Core ✓ → Enterprise ✓ → Cloud & Craft
Cloud & Craft · 3 — Microservices & interviews · ~6 min · Module 5: Modern Enterprise Patterns
What is this?
Enterprise specifications often expose Expression
Why should you care?
ShopNest “open orders over 1000” must filter in the database, not load millions into memory.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
using System.Linq.Expressions;
public interface IExpressionSpec<T>
{
Expression<Func<T, bool>> ToExpression();
}
public sealed class OpenHighValueSpec : IExpressionSpec<OrderRow>
{
public Expression<Func<OrderRow, bool>> ToExpression() =>
o => o.Status == "Open" && o.Total >= 1000;
}
public sealed record OrderRow(string Status, decimal Total);
var spec = new OpenHighValueSpec().ToExpression().Compile();
Console.WriteLine(spec(new OrderRow("Open", 2500)));
// In EF: db.Orders.Where(new OpenHighValueSpec().ToExpression());
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Expression specs compose into IQueryable.
- In-memory Compile helps unit tests.
- This deepens the earlier boolean specification lesson toward EF.
Practice next
- Compile and test the sample.
- Use Where(spec.ToExpression()) in EF.
- Compose AndAlso expressions carefully.
- Parameterize min total.
- Add AsNoTracking query.
Remember
Expressions for SQL. Same rule names as domain. Filter in the database.
ShopNest EF open-order query
Ops list uses OpenHighValueSpec in EF Where.
Outcome: SQL filters; memory stays calm.
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!