Hello TetleyK, I read the second part of the documentation.
But as you can see in my code I do not use
My goal is to encapsulate all this logic duplicate field in a custom validation.
I even try to create Expression linq to achieve this goal:
Usage:
But as you can see in my code I do not use
Must
.My goal is to encapsulate all this logic duplicate field in a custom validation.
I even try to create Expression linq to achieve this goal:
protected override bool IsValid(PropertyValidatorContext context)
{
if (context.PropertyValue == null || string.IsNullOrWhiteSpace(context.PropertyValue.ToString()))
return true;
var currentId = Expression.Lambda<Func<int>>(PropertyId).Compile()(); // Get Current ID
// p => p.Id != currentId
ParameterExpression pId = Expression.Parameter(typeof(int), "Id");
ConstantExpression cId = Expression.Constant(currentId, typeof(int));
BinaryExpression notCurrent = Expression.NotEqual(pId, cId);
Expression<Func<int, bool>> NotCurrentExpr =
Expression.Lambda<Func<int, bool>>(
notCurrent,
new ParameterExpression[] { pId });
// p.{PropertyName} == context.PropertyValue
ParameterExpression pUnique = Expression.Parameter(typeof(string), context.PropertyName);
ConstantExpression cUnique = Expression.Constant(context.PropertyValue, typeof(string));
BinaryExpression checkUnique = Expression.Equal(pId, cId);
Expression<Func<string, bool>> CheckUniqueExp =
Expression.Lambda<Func<string, bool>>(
checkUnique,
new ParameterExpression[] { pUnique });
if (currentId > 0)
{
var exp = Expression.And(NotCurrentExpr, CheckUniqueExp);
return Repository.All().Provider.CreateQuery(exp);
}
return Repository.All().Any(checkUnique);
}
I've used this logic before (with Must
and method overload) for validation of unique fields. But with so many fields with this same validation decided to encapsulateUsage:
RuleFor(p => p.CNPJ)
.MustBeUnique(p => p.Id, repository);