Creating a Query for the Registration Service

We create query objects instead of using linq because these kinds of queries are associated with the business logic, and wrapping queries into objects allows us to reuse them as well as unit test them. Also, naming them with a class gives us more clues about the purpose of the query rather than on-the-fly queries.

Follow these steps to create a query for the registration service:

In the Queries folder of the Application project, we create a UserExistsQuery class, as follows:


Go to https://goo.gl/3r92QU to access the code.
using RestBuy.Entities;
using System;
using System.Linq.Expressions;
namespace RestBuy.Application.Services.Queries
{
class UserExistsQuery : BaseQuery<User>
{
public UserExistsQuery(string userName) =>
this.UserName = userName;
public string UserName { get; }
public override Expression<Func<User, bool>>
Criteria =>
u => u.UserName == this.UserName;
public override int Take => 1;
}
}

Basically, this query object searches for a user with a given username, and attempts to take the first record by setting Take = 1.

Remember, one of the goals of software engineering is to have readable and understandable code. Short code doesn't always mean good code. So whenever necessary, feel free to create new classes and name them properly.