Sobes.tech
Junior — Middle

Can you explain the concept of CQRS and how it is used to separate commands and queries in application architecture?

sobes.tech AI

Answer from AI

CQRS (Command Query Responsibility Segregation) is an architectural pattern that separates operations that change state (commands) from data reading operations (queries) into different models.

The main idea:

  • Commands modify the system's state without returning data.
  • Queries retrieve data without changing the state.

This separation allows each part to be optimized independently: the command model can be complex and provide business logic, while the query model is designed to be as fast and read-optimized as possible.

In C#, this is often implemented through separate classes or services for commands and queries, for example:

public interface ICommand {}
public interface IQuery<TResult> {}

public class CreateOrderCommand : ICommand {
    public int ProductId { get; set; }
    public int Quantity { get; set; }
}

public class GetOrderQuery : IQuery<OrderDto> {
    public int OrderId { get; set; }
}

// Handlers for commands and queries implement the corresponding logic

This separation simplifies scaling, testing, and maintaining the application.