How to use FluentValidation in the pattern repository when you need to check the uniqueness, for example, login (checked in the database)?

Explanation:

The solution consists of 4 projects:

enter image description here

The structure of the project RTLservise.Model:

enter image description here

UserValidator class:

  public class UserValidator : AbstractValidator<User> { public UserValidator() { RuleFor(x => x.Login) .Must(CheckUserName) .WithMessage("Login некорректный."); .Must(IsLoginUnique) .WithMessage("Пользователь с таким логином уже зарегистрирован."); } private bool CheckUserName(string login) { if (login == null) return false; string pattern = @"^[a-zA-Z][a-zA-Z0-9-_\.]{1,49}$"; Regex regex = new Regex(pattern); return regex.IsMatch(login); } } 

CheckUserName was easy.
BUT: Check the user for uniqueness (execute the function uf_Bit_exists_login ), for example:

  public bool IsLoginUnique(string login) { if (login == null) { return false; } using (var connection = new SqlConnection(_connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandType = CommandType.StoredProcedure; command.CommandText = "uf_Bit_exists_login"; var returnValue = command.Parameters.AddWithValue("@login", login); returnValue.Direction = ParameterDirection.ReturnValue; command.ExecuteNonQuery(); return (bool)returnValue.Value; } } } 

And here all the tests immediately fall.

Is it correct to place the check related to connecting to the database exactly in the class of the validator ??

Of course I wanted something, like:

 IUserRepository _repository = new UserRepository(); 

And then check:

  _repository.IsLoginUnique(string) 

BUT: this is impossible, because There are cyclical references :( Then can transfer the validation logic to the service? It is not clear with this design approach, where is the general check?

  • one
    I believe that there should be conditional validation "if the validation of properties has passed, then only then go into the database to check." And on this topic there is my issue on the githaba and the answer of the form "there is no such thing and it is not planned to contribute." Thus, we proceed to solving the "chain of validators" and the set of validators ValidatorsChain, that is, an abstraction a level higher - if the first validator has passed, then the second one can be called, which the DB will check. There is no finished ValidatorsChain in lib, I haven't reached my hands, but you can write. - vitidev
  • What is the problem to forward the IUserRepository repository through the constructor from DI? - Liashenko V

0