CQRS Pattern With C# (Part 1)

Understand CQRS pattern in a real world application

Abdelmajid BACO

--

CQRS Pattern with C#
Image from Pexels

CQRS is the acronym for Command Query Responsibility Segregation. The core idea of this pattern is to separate Read and Update operations by using different models to handle the treatment. We use commands to update data, and queries to read data.

In this article I’ll aim to clarify all parts of CQRS pattern with pretty schema and code example.

Traditional Architecture

The following schema shows a traditional architecture used to query and update a database. The same model is used to write and read data.

Command and Query with traditional architecture (From Microsoft Docs)
Command and Query with traditional architecture (From Microsoft Docs)

This architecture is perfect for a small project, but in more sophisticated applications, it will be laborious to implement new features. For example, the application needs to display some information on different screens. So, many queries are requested to database, then all responses are mapped to a specific data transfer object. Another example is when the application tries to update model with some data validation, maybe a complex business rules. In conclusion, the model does many things!

You will notice that the model becomes more and more complicated. To avoid this problem, let’s look at the contribution of the CQRS pattern in the next chapter.

New Architecture With CQRS

The CQRS pattern proposal, consists of separating the read and update / write operations into different models. As shown in the following schema,
two models are involved in this architecture, the first manages the read operations and the second manages the write operations.

Command Query Responsibility Segregation architecture (From Microsoft Docs)
Command Query Responsibility Segregation architecture (From Microsoft Docs)

According to Microsoft documentation, the CQRS pattern must follow the three principles below:

1) Commands should be task based, rather than data centric. (“Book hotel room”, not “set ReservationStatus to Reserved”).

--

--

Abdelmajid BACO

Senior Full Stack .Net / Angular Developer, Cloud & Azure DevOps, Carrier Manager, Husband, and Father.