×

iFour Logo

Introduction to Command Query Responsibility Segregation (CQRS)

Kapil Panchal - November 10, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Introduction to Command Query Responsibility Segregation (CQRS)

What is API?


Before knowing what is CQRS first we know about API. In simple words API is like an interface that is a set of functions and methods which allow programmers to access its specific features and data of an application.

Features of Asp.Net Web API


  • It supports different MVC features like controllers, routing, model binders, action results, filter, IOC container, or dependency injection that makes it simpler and easier to develop.

  • We can create ASP.NET web API which is formatted by Web API's MediaTypeFormatter in XML or JSON or any other format which you want to add as MediaTypeFormatter.

  • It supports convention-based Create, Update, and Delete Actions from where it works with HTTP verbs like GET, POST, PUT and DELETE.

  • We can create WebAPI in different ways which are accepted and generatecontent which are not be object-oriented like the image or any other document files.

  • The ASP.NET Web API gives responses in the HTTP status code.

  • It can be hosted in the application or on IIS.

What is CQRS?


CQRS stands for "Command Query Responsibility Segregation". CQRS is a pattern which is described by Greg Young. Its main portion is the notion that you can use a different model to update information than the model you use to read information. For some situations, this separation is often valuable but beware that for many systems CQRS adds risky complexity.

The mainstream approach people use for interacting with a data system is to treat it as a CRUD data-store. By this, we mean that we have a model of some record structure where we will create new records, read it and update it, and delete records when we're done with them. In the simplest case, our interchange is all about storing and retrieving these records

As our needs become more sophisticated we steadily move far away from that model. We might want to seem at the knowledge during different types the record store, perhaps collapsing multiple records into one, or forming virtual records by combining information for different places.

Benefits Of CQRS


Independentscaling

CQRS allows the read and write workloads to scale independently, and should output in fewer lock contentions.

Security

Command Query Responsibility Segregation is easier to confirm that only the right domain entities are performing writes on the data.

Separation of concerns

Differentiate the read and write side may result in models which are more maintainable and flexible. All hard business logic goes into the Write Model and the read model is easy to compare to the write model.

Simpler queries

By storing a materialized view within the read database, the applicationcan avoid complex joins when querying.

Let's start to allow CQRS with program

To Follow my example first of all you need to clone my project from my GitHub repository.

When your cloning completes from my Repository open the CQRSDemo.sln solution.

 

After Cloning my project code let's understand structure of solution

The solution is the ASP.NET core template with some manually included folders. In solution have two folders manually included Commands and Queries.

In command folder you will find the classes which implements the command part of the pattern and in queries folder you found the classes which is related to queries part of pattern.

Controllers


In the controller, you will find the PostController class in which has two methods first is Get () and the second is SavePost() method. You can see the Save method is implemented as a command, and the second one the Get method is implemented as a query.

The Code of the controller class is below.

	[ApiController]
    public class PostsController :ControllerBase
    {
        private readonlyIQueriesService _queries;
        private readonlyICommandService _commands;
        public PostsController(IQueriesService queries, ICommandService commands)
       {
            _queries = queries ?? throw new ArgumentNullException(nameof(queries));
            _commands = commands ?? throw new ArgumentNullException(nameof(commands));
        }
       // GET api/values
        [HttpGet]
        public asyncTask Get()
        {
            return (await _queries.GetAllPostId()).ToList();
        }
        // POST api/values
        [HttpPost]
        public void SavePost([FromBody] SavePostDto value)
        {
            _commands.SavePost(value.Title, value.Body);
        }
    }
				

As you see, we build with constructor the query service and command service are done in this controller. Initially first we configure ASP.NET core dependency injection framework to handle all related situations.

In this controller the Get method calls the query service and savepost method calls the command service.As we know a query is do operation only Read-Only and other side command is do action which is modifies the state of system.

Now let's see how this service are implemented.

Commands Folder


It contains an interface which states what commands service is capable for basic implementation.

Below is the ICommandService interface:

public interface ICommandService
    {
        Task SavePost(string title, string body);
    }
public class CommandService :ICommandService
    {
        private readonlyBlogContext _context;
        public CommandService(BlogContext context)
        {
_context=context??throw new ArgumentNullException(nameof(context));
        }
        public async Task SavePost(string title, string body)
        {
            var post = new Post() { Title = title, Body = body };
            await _context.Posts.AddAsync(post );
            await _context.SaveChangesAsync();
            return post ;
        }
    }

The implementation of this interface is based on Entity Framework Core which store data inside a SQL Service instance.

Wants to Talk with Our Highly Skilled .Net Core Developer ? Contact now.

Queries


In Command folder you can see a IQueriesService which describes query service.

public interface IQueriesService
  {
  Task GetAllPostId();
  }
				

IQueriesService interfacecontains a Task GetAllPostId(); method to get a unique identifiers in database.

public class QueriesService :IQueriesService
{
  private readonly string _connectionString;
    public QueriesService(string connectionString)
    {
      if (string.IsNullOrEmpty(connectionString))
    {
    throw new ArgumentException("message", nameof(connectionString));
    }
      _connectionString = connectionString;
    }
    public async Task GetAllPostId()
    {
      using (var conn = new SqlConnection(_connectionString))
    {
    conn.Open();
    return await conn.QueryAsync("SELECT Id FROM dbo.Posts;");
    }
  }
}
				

As you have seen the query and command are different and separated tech for read -only we use entity framework.

One of the best advantages of CQRS is we can build highly optimized read operation and differentiated the operations for a different data store.

Conclusion


We hope with this blog post you will fully understand CQRS pattern and how to implement it in API and allow it CQRS is a pattern. We do programming for commands and queries in different models it is use full for easy to implement and more optimized structure hard business logic is do in write model and read model is easy then write model.In short CQRS is pattern in which can easily read and write and side may result in models which are more maintainable and flexible.

Introduction to Command Query Responsibility Segregation (CQRS) What is API? Before knowing what is CQRS first we know about API. In simple words API is like an interface that is a set of functions and methods which allow programmers to access its specific features and data of an application. Features of Asp.Net Web API It supports different MVC features like controllers, routing, model binders, action results, filter, IOC container, or dependency injection that makes it simpler and easier to develop. We can create ASP.NET web API which is formatted by Web API's MediaTypeFormatter in XML or JSON or any other format which you want to add as MediaTypeFormatter. It supports convention-based Create, Update, and Delete Actions from where it works with HTTP verbs like GET, POST, PUT and DELETE. We can create WebAPI in different ways which are accepted and generatecontent which are not be object-oriented like the image or any other document files. The ASP.NET Web API gives responses in the HTTP status code. It can be hosted in the application or on IIS. What is CQRS? CQRS stands for "Command Query Responsibility Segregation". CQRS is a pattern which is described by Greg Young. Its main portion is the notion that you can use a different model to update information than the model you use to read information. For some situations, this separation is often valuable but beware that for many systems CQRS adds risky complexity. The mainstream approach people use for interacting with a data system is to treat it as a CRUD data-store. By this, we mean that we have a model of some record structure where we will create new records, read it and update it, and delete records when we're done with them. In the simplest case, our interchange is all about storing and retrieving these records As our needs become more sophisticated we steadily move far away from that model. We might want to seem at the knowledge during different types the record store, perhaps collapsing multiple records into one, or forming virtual records by combining information for different places. Read More: Understanding Validation Tag Helpers In Asp.net Core Benefits Of CQRS Independentscaling CQRS allows the read and write workloads to scale independently, and should output in fewer lock contentions. Security Command Query Responsibility Segregation is easier to confirm that only the right domain entities are performing writes on the data. Separation of concerns Differentiate the read and write side may result in models which are more maintainable and flexible. All hard business logic goes into the Write Model and the read model is easy to compare to the write model. Simpler queries By storing a materialized view within the read database, the applicationcan avoid complex joins when querying. Let's start to allow CQRS with program To Follow my example first of all you need to clone my project from my GitHub repository. When your cloning completes from my Repository open the CQRSDemo.sln solution.   After Cloning my project code let's understand structure of solution The solution is the ASP.NET core template with some manually included folders. In solution have two folders manually included Commands and Queries. In command folder you will find the classes which implements the command part of the pattern and in queries folder you found the classes which is related to queries part of pattern. Controllers In the controller, you will find the PostController class in which has two methods first is Get () and the second is SavePost() method. You can see the Save method is implemented as a command, and the second one the Get method is implemented as a query. The Code of the controller class is below. [ApiController] public class PostsController :ControllerBase { private readonlyIQueriesService _queries; private readonlyICommandService _commands; public PostsController(IQueriesService queries, ICommandService commands) { _queries = queries ?? throw new ArgumentNullException(nameof(queries)); _commands = commands ?? throw new ArgumentNullException(nameof(commands)); } // GET api/values [HttpGet] public asyncTask Get() { return (await _queries.GetAllPostId()).ToList(); } // POST api/values [HttpPost] public void SavePost([FromBody] SavePostDto value) { _commands.SavePost(value.Title, value.Body); } } As you see, we build with constructor the query service and command service are done in this controller. Initially first we configure ASP.NET core dependency injection framework to handle all related situations. In this controller the Get method calls the query service and savepost method calls the command service.As we know a query is do operation only Read-Only and other side command is do action which is modifies the state of system. Now let's see how this service are implemented. Commands Folder It contains an interface which states what commands service is capable for basic implementation. Below is the ICommandService interface: public interface ICommandService { Task SavePost(string title, string body); } public class CommandService :ICommandService { private readonlyBlogContext _context; public CommandService(BlogContext context) { _context=context??throw new ArgumentNullException(nameof(context)); } public async Task SavePost(string title, string body) { var post = new Post() { Title = title, Body = body }; await _context.Posts.AddAsync(post ); await _context.SaveChangesAsync(); return post ; } } The implementation of this interface is based on Entity Framework Core which store data inside a SQL Service instance. Wants to Talk with Our Highly Skilled .Net Core Developer ? Contact now. See here Queries In Command folder you can see a IQueriesService which describes query service. public interface IQueriesService { Task GetAllPostId(); } IQueriesService interfacecontains a Task GetAllPostId(); method to get a unique identifiers in database. public class QueriesService :IQueriesService { private readonly string _connectionString; public QueriesService(string connectionString) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentException("message", nameof(connectionString)); } _connectionString = connectionString; } public async Task GetAllPostId() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); return await conn.QueryAsync("SELECT Id FROM dbo.Posts;"); } } } As you have seen the query and command are different and separated tech for read -only we use entity framework. One of the best advantages of CQRS is we can build highly optimized read operation and differentiated the operations for a different data store. Conclusion We hope with this blog post you will fully understand CQRS pattern and how to implement it in API and allow it CQRS is a pattern. We do programming for commands and queries in different models it is use full for easy to implement and more optimized structure hard business logic is do in write model and read model is easy then write model.In short CQRS is pattern in which can easily read and write and side may result in models which are more maintainable and flexible.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
HR Analytics Dashboard – Key Metrics & Examples
HR Analytics Dashboard – Key Metrics & Examples

HR analytics, generally known as People Analytics, could be a solid answer to those sceptics who believe that the HR department's role is just about hiring and making offers! This...

10 Executive Dashboard Examples for Consultants and CEOs
10 Executive Dashboard Examples for Consultants and CEOs

There is a principle behind every business. “If you don’t keep track of essentials, you won’t get clear direction, eventually causing your company to stumble.” To manage this scenario,...

How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...