Reputation: 16300
I have a class and my validation looks like this:
public ValidationResult Validate(CustomerType customerType)
{
CustomerType Validator validator = new CustomerTypeValidator();
validator.RuleFor(x => x.Number).Must(BeUniqueNumber);
return validator.Validate(customerType);
}
public bool BeUniqueNumber(int number)
{
//var result = repository.Get(x => x.Number == customerType.Number)
// .Where(x => x.Id != customerType.Id)
// .FirstOrDefault();
//return result == null;
return true;
}
The CustomerTypeValidator is a basic validator class that validates string properties.
I also add a new rule to check if the number is unique in the db. I do it in this class because there's a reference to the repository. The validator class has no such reference.
The problem here is that the BeUniqueNumber method should have a CustomerType parameter. However when I do this, I get an error on the RuleFor line above because 'Must' needs an int as a parameter.
Is there a way around this?
Upvotes: 2
Views: 15295
Reputation: 47375
Can you try this?
public ValidationResult Validate(CustomerType customerType)
{
CustomerTypeValidator validator = new CustomerTypeValidator();
validator.RuleFor(x => x).Must(HaveUniqueNumber);
return validator.Validate(customerType);
}
public bool HaveUniqueNumber(CustomerType customerType)
{
var result = repository.Get(x => x.Number == customerType.Number)
.Where(x => x.Id != customerType.Id)
.FirstOrDefault();
return result == null;
//return true;
}
You should also be able to do this:
public ValidationResult Validate(CustomerType customerType)
{
CustomerTypeValidator validator = new CustomerTypeValidator();
validator.RuleFor(x => x.Number).Must(BeUniqueNumber);
return validator.Validate(customerType);
}
public bool BeUniqueNumber(CustomerType customerType, int number)
{
var result = repository.Get(x => x.Number == number)
.Where(x => x.Id != customerType.Id)
.FirstOrDefault();
return result == null;
//return true;
}
"I also add a new rule to check if the number is unique in the db. I do it in this class because there's a reference to the repository."
Well, why can't you give your validator a reference to the repository too?
CustomerTypeValidator validator = new CustomerTypeValidator(repository);
Upvotes: 3