What is the CQRS pattern in C#?
Answer
CQRS (Command Query Responsibility Segregation) separates read operations (Queries) from write operations (Commands) into distinct models and handlers. Commands: represent intent to change state — no return value (or minimal acknowledgment). Queries: return data — no side effects. In C# with MediatR library: public record GetUserQuery(int Id) : IRequest<UserDto>;. Handler: public class GetUserHandler : IRequestHandler<GetUserQuery, UserDto> { public async Task<UserDto> Handle(GetUserQuery q, CancellationToken ct) { return await _repo.GetDtoByIdAsync(q.Id); } }. Controller: return Ok(await _mediator.Send(new GetUserQuery(id)));. Benefits: (1) Separate read/write models optimized for their purpose. (2) Scale reads and writes independently. (3) Enables event sourcing. (4) Clear separation of concerns. Drawbacks: complexity — don't apply CQRS to simple CRUD applications without justification. Best suited for complex domain logic with high read/write ratio differences.
More C# / .NET Questions
View all →- Intermediate What is ASP.NET Core and how does it differ from ASP.NET Framework?
- Intermediate What is middleware in ASP.NET Core?
- Intermediate What is dependency injection in ASP.NET Core?
- Intermediate What is Entity Framework Core?
- Intermediate What is the difference between eager, lazy, and explicit loading in EF Core?