Skip to main content

Lesson 6 of 8

CQRS Basics - Commands vs Queries

CQRS (Command Query Responsibility Segregation) separates write operations (Commands) from read operations (Queries). Commands mutate state and often have business rules. Queries read state optimally without loading entity graphs, using projection queries for performance.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

MediatR Commands & Queries

MediatR Commands & Queries
using MediatR;

// ━━ Command - mutates state, returns Result ━━
public record CreateProductCommand(
    string Name, decimal Price, Guid CategoryId, int Stock, string? Description)
    : IRequest<Result<ProductDto>>;

public class CreateProductHandler(IUnitOfWork uow, IMapper mapper)
    : IRequestHandler<CreateProductCommand, Result<ProductDto>>
{
    public async Task<Result<ProductDto>> Handle(
        CreateProductCommand command, CancellationToken ct)
    {
        // Business logic here (validation, checks, etc.)
        var product = new ProductEntity { Id = Guid.NewGuid(), Name = command.Name, Price = command.Price };
        uow.Products.Add(product);
        await uow.SaveChangesAsync(ct);
        return Result<ProductDto>.Success(mapper.Map<ProductDto>(product));
    }
}

// ━━ Query - read-only, optimized projection ━━
public record GetProductsQuery(
    Guid? CategoryId, string? Search, string? Cursor, int Limit = 20)
    : IRequest<CursorPage<ProductDto>>;

public class GetProductsHandler(IReadDbContext readDb)
    : IRequestHandler<GetProductsQuery, CursorPage<ProductDto>>
{
    public async Task<CursorPage<ProductDto>> Handle(
        GetProductsQuery query, CancellationToken ct)
    {
        // Use read-optimized context or dapper for projections
        var items = await readDb.Products
            .Where(p => query.CategoryId == null || p.CategoryId == query.CategoryId)
            .Where(p => query.Search == null || p.Name.Contains(query.Search))
            .Select(p => new ProductDto(p.Id, p.Name, p.Price, p.CategoryName))
            .Take(query.Limit + 1)
            .ToListAsync(ct);

        var hasNext = items.Count > query.Limit;
        if (hasNext) items.RemoveAt(items.Count - 1);
        return new CursorPage<ProductDto>([.. items], null, hasNext, query.Limit);
    }
}

// ━━ MediatR pipeline behavior - cross-cutting concerns ━━
// Logging → Validation → Handler (nest like middleware)
public class ValidationBehavior<TRequest, TResponse>(
    IEnumerable<IValidator<TRequest>> validators)
    : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    public async Task<TResponse> Handle(
        TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        var failures = validators
            .Select(v => v.Validate(request))
            .SelectMany(r => r.Errors)
            .Where(f => f is not null)
            .ToList();

        if (failures.Count > 0)
            throw new FluentValidation.ValidationException(failures);

        return await next();
    }
}

// Controller just dispatches - no business logic:
[HttpPost]
public async Task<IActionResult> Create(CreateProductCommand command, IMediator mediator, CancellationToken ct)
{
    var result = await mediator.Send(command, ct);
    return result.IsSuccess ? CreatedAtAction(nameof(GetById), new { id = result.Value!.Id }, result.Value) : Conflict(result.Error);
}

// Placeholder
interface IReadDbContext { IQueryable<ProductReadModel> Products { get; } }
class ProductReadModel { public Guid Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; } public Guid CategoryId { get; set; } public string CategoryName { get; set; } = ""; }
class ProductEntity { public Guid Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; } }
record ProductDto(Guid Id, string Name, decimal Price, string CategoryName);
interface IUnitOfWork { IProductRepository Products { get; } Task<int> SaveChangesAsync(CancellationToken ct); }
interface IProductRepository { void Add(ProductEntity p); }
interface IMapper { TDest Map<TDest>(object src); }
interface IValidator<T> { FluentValidation.Results.ValidationResult Validate(T value); }
record Result<T>(bool IsSuccess, T? Value = default, string? Error = null) { public static Result<T> Success(T v) => new(true, v); }
class CursorPage<T>(List<T> Items, string? NextCursor, bool HasNextPage, int Limit);
interface IPipelineBehavior<TRequest, TResponse> { Task<TResponse> Handle(TRequest r, RequestHandlerDelegate<TResponse> next, CancellationToken ct); }
delegate Task<TResponse> RequestHandlerDelegate<TResponse>();

Tip

Tip

Practice CQRS Basics Commands vs Queries in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of CQRS Basics Commands vs Queries from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with CQRS Basics Commands vs Queries is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done