Ali
Ali

Reputation: 1409

How to limit the number of query classes in CQRS?

I am implementing CQRS and I am a little confused on the how quickly number of queries are getting. I have googled it too but due to variety of flavors of CQRS I am not getting any appropriate solution. Perhaps I'm doing something wrong here? Here's my code and respective queries.

class User {
   public int Id { get; set; }   
   public string Username { get; set; }
   public string Status { get; set; }
   public string Role { get; set; }
   // ...
}

And I want to find user by its username, so I have written query for it

abstract class Query<TResult> { }
class FindUserByStatusQuery : Query<IEnumerable<User>> {
       public string Status;
}

and the respective handler for it

interface IQueryHandler<TQuery, TResult> where TQuery : Query<TResult>
{ 
    TResult Handle(TQuery query);     
} 

class FindUserByStatusQueryHandler : IQueryHandler<FindUserByStatusQuery, IEnumerable<User>> 
{
               public IEnumerable<User> Handle(FindUsersByAcountStatusQuery query)
               {   
                   using (Entities db = new Entities()) 
                   {
                      status = query.status.ConvertToString();
                      return db.Users.Where(u =>  u.Status.Contains(status)).ToArray();
                   }
               }
}

Now, I want to look-up user by other fields too like by Id or by multiple fields (by both status & role). And there could be more queries like that.

My question is do I need to create separate query classes for them? Wouldn't that make number of queries quite high? How can I limit that?

Upvotes: 2

Views: 901

Answers (1)

Baldy
Baldy

Reputation: 3669

I find the best approach is to be pragmatic - make the query fit the context of the current situation, and dont think beyond that.

You say they could query by status and role at the same time, so include both of those properties on the query object.

If you reuse the query 'somewhere else' in the domain, and it needs further search criteria, create a new query specifically for that domain problem.

Free yourself from the burden of 'limiting code' and deal with each situation separately. Creating objects that deal with multiple domain scenarios leads to complexity, regression issues and brittle classes.

Give your types a single responsibility

Upvotes: 7

Related Questions