As an application grows, managing business logic inside controllers and services becomes more difficult. A service that initially handles a few database operations can eventually contain validation, data retrieval, business rules, and updates in the same class.
The problem isn’t necessarily Entity Framework Core or how the services are written. It’s that reading and modifying data often have different requirements, but we continue handling them through the same structure.
This is where Command Query Responsibility Segregation (CQRS) becomes useful.
Understanding CQRS
CQRS separates application operations into two responsibilities.
- Commands perform actions that change the application’s state, such as creating an employee, approving a request, or updating an order.
- Queries retrieve information without modifying the application’s state, such as getting employee details or listing pending requests.
The separation doesn’t require different databases, microservices, or complex infrastructure.
For many .NET applications, CQRS can be implemented within a single application using the same EF Core DbContext.
The main objective is to keep operations focused on their intended responsibilities.
Where EF Core and MediatR Fit
EF Core handles database access, entity tracking, and persistence. MediatR provides a way to dispatch requests to their corresponding handlers.
MediatR doesn’t implement CQRS automatically. It provides request and handler abstractions that make organizing commands and queries easier.
Consider a hypothetical employee management application. Instead of creating an EmployeeService containing every employee operation, we can organize the application around individual use cases.
For example:
Features/
Employees/
Commands/
CreateEmployee/
CreateEmployeeCommand.cs
CreateEmployeeHandler.cs
Queries/
GetEmployeeById/
GetEmployeeByIdQuery.cs
GetEmployeeByIdHandler.csEach handler has a specific responsibility, making the implementation easier to locate, test, and maintain.
Implementing a Command
Suppose we need to register a new employee.
The code examples in this article are simplified for demonstration purposes and are not taken from an actual production project.
Using C# with EF Core and MediatR, we can define a command and its handler:
public record CreateEmployeeCommand(
string FirstName,
string LastName
) : IRequest<Guid>;
public class CreateEmployeeHandler(
AppDbContext dbContext)
: IRequestHandler<CreateEmployeeCommand, Guid>
{
public async Task<Guid> Handle(
CreateEmployeeCommand request,
CancellationToken cancellationToken)
{
var employee = new Employee
{
Id = Guid.NewGuid(),
FirstName = request.FirstName,
LastName = request.LastName
};
dbContext.Employees.Add(employee);
await dbContext.SaveChangesAsync(
cancellationToken);
return employee.Id;
}
}The command describes what the application needs to accomplish. The handler performs the operation.
In a real application, we would also need appropriate validation, authorization, and business rules before saving the employee.
An important design consideration is that commands should represent business actions rather than simply mirror database operations.
For example, ApproveLeaveRequestCommand communicates business intent more clearly than UpdateLeaveStatusCommand.
Implementing a Query
Retrieving employee information has different requirements. We don’t need to modify an entity or track its changes.
public record GetEmployeeByIdQuery(Guid Id)
: IRequest<EmployeeDto?>;
public class GetEmployeeByIdHandler(
AppDbContext dbContext)
: IRequestHandler<GetEmployeeByIdQuery, EmployeeDto?>
{
public async Task<EmployeeDto?> Handle(
GetEmployeeByIdQuery request,
CancellationToken cancellationToken)
{
return await dbContext.Employees
.AsNoTracking()
.Where(e => e.Id == request.Id)
.Select(e => new EmployeeDto(
e.Id,
e.FirstName,
e.LastName))
.FirstOrDefaultAsync(cancellationToken);
}
}Here, EmployeeDto is a simple record containing the three selected fields.
The query returns only the information needed by the caller. It doesn’t expose the entire database entity.
AsNoTracking() also makes the read-only intent explicit. EF Core doesn’t need to track entity changes for this operation. In this example, the query projects directly into a DTO, so no entity instances are materialized for tracking anyway.
Why the Separation Matters
The advantage becomes more noticeable when business requirements grow.
Suppose employee registration requires checking company-specific rules, validating employment details, and creating related records. These responsibilities can remain within the command workflow without affecting employee search or reporting queries.
Similarly, a reporting query can be optimized independently without changing the logic responsible for updating employee information.
There are still important considerations.
CQRS doesn’t automatically improve performance. Poorly designed queries remain expensive, and commands can still introduce concurrency problems. Authorization and tenant isolation must also be enforced regardless of whether an operation is a command or query.
Adding MediatR introduces another abstraction and additional classes. For a small application with straightforward CRUD operations, this might create more maintenance work than it solves.
Separating handlers also doesn’t require separate databases. Using independent read and write databases introduces additional synchronization and consistency concerns that many applications don’t need.
When I Would Consider CQRS
I would consider CQRS when an application has increasingly complex business workflows, different read and write requirements, or features that are becoming difficult to maintain inside shared services.
For simpler applications, conventional application services may be sufficient.
The important decision isn’t whether every project should use CQRS. It’s whether separating responsibilities makes the application easier to understand and change.
EF Core already provides the database capabilities, while MediatR helps organize request handling. Used together, they offer a practical way to apply CQRS without immediately introducing distributed architecture.
Start with the separation of commands and queries. Add more complexity only when the application’s requirements justify it.






