CQRS is a command and query responsibility pattern that separates read and write operations into different models. Commands (Insert/update) operations will have a separate model. Queries (read) operations will have a separate model. By separating them, it allows models to be more focused on the tasks that they are performing.
Traditionally, commands will have a large model as it would map the model to the whole database table with some business logic validating the model before saving it the database. Whereas, on the other hand, queries will have a simple model, returning a dataset according to UI requirements.
Traditional vs CQRS
In traditional applications, we use the same data model for read and write operations. It is good for simple CRUD applications but if you have a large complex application which has a large model. It get’s really difficult to manage it as every other change can cause issues in testing with additional bloated code.
When we use CQRS, we can either have one database or we have can have two databases, one for commands and others for queries. If we create two databases then we have to keep them in sync. This is the additional work you have to do.
How to implement it?
You will see two folders, one for command and another for the query. Query folder has one model class and one handler. I am using a mediator pattern here, which I will explain in my other blog post.
In the following image, you can see the handler class receives the query model and makes a query to the database to get all users from the database.
In the following image, you can see the handler class receives the command model and makes a write operation to save the user in the database.
There are pros and cons to everything. Some of you may feel that implementing CQRS may add additional complexity to the project. In my opinion, It comes down to the use case of the project and how you use this pattern. I have also made a working demo app on GitHub with the CQRS pattern.