How was your PropertyValidator code?
I'm trying to do this right now!
Create a PropertyValidator
In PropertyValidation, how to get current property to use in Linq Expression?
How to pass (or get) Id of object?
I'm trying to do this right now!
Create a PropertyValidator
public class UniqueValidator<T> : PropertyValidator
where T: class, IEntity
{
public UniqueValidator(IRepository<T> repository)
: base("{PropertyName} já existe!")
{ }
protected override bool IsValid(PropertyValidatorContext context)
{
if (context.PropertyValue == null || string.IsNullOrWhiteSpace(context.PropertyValue.ToString()))
return true;
// If {HowToGetId?} > 0, is edit
// return repository.All().Any(p => p.Id != {HowToGetId?} && p.{HowToGetPropertyByExpression?} == nome)
// return repository.All().Any(p => p.{HowToGetPropertyByExpression?} == nome)
}
}
Then RuleBuilderExtensionspublic static IRuleBuilderOptions<T, TElement> MustBeUnique<T, TElement, TEntity>(this IRuleBuilder<T, TElement> ruleBuilder, IRepository<TEntity> repository)
where TEntity : class, IEntity
{
return ruleBuilder.SetValidator(new UniqueValidator<TEntity>(repository));
}
And usage:public class RegionalValidator : AbstractValidator<RegionalViewModel>
{
public RegionalValidator(IRepository<Regional> repositorio)
{
RuleFor(p => p.Nome)
.MustBeValidName()
.MustBeUnique(repositorio); // How to pass Id of object?
}
}
__Basically the question is:__ In PropertyValidation, how to get current property to use in Linq Expression?
How to pass (or get) Id of object?