C#C
C#3y ago
7 replies
TJacken

❔ Validate list of objects after reading excel file

Hi all, how would you validate data from excel file with fluent validation?

I have method which will read data from excel file and return me list of person objects. After read I call validator to validate data from excel file. Person email must be unique, so it shouldn't exist in database when I read data and it shouldn't be duplicated in excel file.

Is it good approach to inject repository in validator or just collect all emails as list and pass it to validator? If I use that approach what if someone else insert person with email in parallel with my operation?

Person class:

public class Person
{
    public string FullName { get; set; }

    public string Email { get; set; }

    public string City { get; set; }
}


Person validator class:
public class PersonValidator : AbstractValidator<Person>
{
    private readonly IPersonRepository _personRepository;
    private readonly List<Person> _peopleFromExcelFile;

    public PersonValidator(IPersonRepository personRepository, List<Person> peopleFromExcelFile)
    {
        _personRepository = personRepository;
        _peopleFromExcelFile = peopleFromExcelFile;

        RuleFor(x => x.FullName)
            .NotEmpty()
            .WithMessage("Full name is empty!");

        RuleFor(x => x.Email)
            .NotEmpty()
            .WithMessage("Email is empty");
            
        RuleFor(x => x.Email)
            .Must(PersonMailDoNotExistInRepository)
            .WithMessage("Email already exists in database");

        RuleFor(x => x.Email)
            .Must(EmailIsNotDuplicateInExcelFile)
            .WithMessage("Email is duplicated in excel file");
    }

    private bool PersonMailDoNotExistInRepository(string email)
    {
        return _personRepository.GetByEmail(email) == null;
    }

    private bool EmailIsNotDuplicateInExcelFile(string email)
    {
        return _peopleFromExcelFile.Count(x =>  x.Email == email) == 1;
    }
}
Was this page helpful?