CQRS pattern with ASP.NET CORE

M. Haris Tauqir
Awesome .Net
Published in
2 min readJun 13, 2022

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. Separating them, 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 to 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 reading and writing operations. It is good for simple CRUD applications but if you have a large complex application that has a large model. It gets really difficult to manage it like 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 the 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. The 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.

Query:

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.

Command:

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.

Conclusion:

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.

--

--

M. Haris Tauqir
Awesome .Net

A software developer who loves learning how things work…