
Imagine you are a developer responsible for maintaining an HR employee portal. This is the Employee class:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public bool IsRemote { get; set; }
public int DepartmentID { get; set; }
public override string ToString()
{
return $"Id: {Id}, Name: {Name}, IsRemote: {(IsRemote ? "Yes" : "No")}, DepartmentID: {DepartmentID}";
}
}One day, HR asks you to find employees whose names start with the letter “A”. You create a method like this:
public List<Employee> GetNameByInitial(string queryName) {
var result = _db.Employees
.Where(e => e.Name.StartsWith(queryName))
.ToList();
return result;
}Then the next day, HR needs something like get employee by department, by if they are remote, by finance department and work from home etc.
Eventually, you will suffer a method explosion by keep creating new method
GetByIsRemote()
GetByDepartment()
GetDepartmentAndIsRemote()
GetBySalary()IThe Specification Pattern represents domain business rules as reusable, composable objects.
The Specification Pattern represents domain business rules as reusable, composable objects.
Think of it this way:
Domain Business Logic answers “What are the rules?”
Specification Pattern answers “How do we represent those rules in code?”
In this example, the Employee class contains data such as Name, DepartmentID, and IsRemote. These properties allow us to define business rules that HR may use when searching for employees.
We start by creating one Specification class for each business rule. For example, one specification checks an employee’s name, another checks the department, and another checks whether the employee works remotely.
First, we create an abstract base class that all concrete Specification classes will inherit from.
public abstract class BaseSpecification <T>
{
public abstract Expression<Func<T, bool>> Criteria { get; }
}As you can see, my base class is an abstract class and accepts a generic type parameter.
The Criteria property is overridden by each concrete Specification to define its own filtering rule.
What and Why Used Expression Tree
Notice that the Criteria property returns an Expression<Func<T, bool>> instead of a Func<T, bool>.
An Expression<Func<T, bool>> represents the filtering logic as an expression tree, not executable code.
You can think of Expression<Func<T, bool>> like this:
Instead of immediately executing a query in memory, such as filtering a list of employees in C#, EF Core builds an expression that describes the query.
When the query is executed, EF Core translates that expression into a SQL statement like:
“SELECT * FROM Employee WHERE DepartmentId = 1”
This SQL is then sent to the database server, where the filtering actually happens.
You might ask, why not use Func<T,bool>?
If we returned a Func<T, bool> instead, the delegate would execute in C# after the data had already been loaded into memory. By returning an Expression<Func<T, bool>>, EF Core can translate the expression into SQL so that the database performs the filtering before sending the results back.
Then, we move to our concrete business specification class.
public class NameSpecification : BaseSpecification<Employee>
{
private readonly string _queryName;
public NameSpecification(string queryName)
{
_queryName = queryName;
}
public override Expression<Func<Employee, bool>> Criteria => e => e.Name.StartsWith(_queryName, StringComparison.OrdinalIgnoreCase);
}We start with the NameSpecification class. This specification defines a business rule that filters employees whose names start with a given string passed into the constructor.
You can now see that the Criteria property has been overridden with a lambda expression that defines the filtering rule. This expression checks whether an employee’s name starts with the provided value.
Notice that this specification does not execute any query. It only defines the rule. EF Core will later translate this expression into SQL when the query is executed.
Same thing goes to the Department and IsRemote specification class
public class DepartmentSpecification : BaseSpecification<Employee>
{
private readonly int _departmentId;
public DepartmentSpecification(int deptId)
{
_departmentId= deptId;
}
public override Expression<Func<Employee, bool>> Criteria => e=>e.DepartmentID == _departmentId;
} public class IsRemoteSpecification : BaseSpecification<Employee>
{
private readonly bool _isRemote;
public IsRemoteSpecification(bool isRemote)
{
_isRemote = isRemote;
}
public override Expression<Func<Employee, bool>> Criteria => e => e.IsRemote == _isRemote;
}For demonstration purposes, we use hardcoded in-memory data. However, the design is intended for EF Core, where the data would come from a database and the expressions would be translated into SQL queries.
public static IQueryable<Employee> GetAll()
{
return new List<Employee> {
new() { Id = 1, Name = "Alice Johnson", DepartmentID = 1, IsRemote = true },
new() { Id = 2, Name = "Alan Martinez", DepartmentID = 1, IsRemote = false },
new() { Id = 3, Name = "Bob White", DepartmentID = 1, IsRemote = true },
new() { Id = 4, Name = "Bella Lee", DepartmentID = 2, IsRemote = false },
new() { Id = 5, Name = "Charlie Brown", DepartmentID = 2, IsRemote = true },
new() { Id = 6, Name = "Carmen Davis", DepartmentID = 3, IsRemote = false },
new() { Id = 7, Name = "Dennis Wilson", DepartmentID = 3, IsRemote = false },
new() { Id = 8, Name = "Diane Taylor", DepartmentID = 4, IsRemote = true },
new() { Id = 9, Name = "Eva Anderson", DepartmentID = 4, IsRemote = false },
new() { Id = 10, Name = "Ellen Thomas", DepartmentID = 5, IsRemote = true },
new() { Id = 11, Name = "Ed Jackson", DepartmentID = 5, IsRemote = false },
}.AsQueryable();
}Then the main class:






Join the conversation! Your thoughts help the community grow.