CQRS Pattern With C# (Part 1)
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.
The following schema shows a traditional architecture used to query and update a database. The same model is used to write and read data.
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.
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”).