Please I need your help to solve FluentValidation issue. I have an old desktop application which I wrote a few years ago. I used FluentValidation Ver 4 and Now I'm trying to upgrade this application to use .Net framework 4.8 and FluentValidation Ver 10, but unfortunately, I couldn't continue because of an exception that I still cannot fix.
I have a base class as follow:
<pre> public abstract class ObjBase : IDataErrorInfo
{
public ObjBase()
{
_Validator = GetValidator();
Validate();
}
protected IValidator _Validator = null;
protected IEnumerable<ValidationFailure> _ValidationErrors = null;
#region Validation
protected virtual IValidator GetValidator()
{
return null;
}
public IEnumerable<ValidationFailure> ValidationErrors
{
get { return _ValidationErrors; }
set { }
}
public void Validate()
{
if (_Validator != null)
{
ValidationResult results = _Validator.Validate(this);
_ValidationErrors = results.Errors;
}
}
public virtual bool IsValid
{
get
{
if (_ValidationErrors != null && _ValidationErrors.Count() > 0)
return false;
else
return true;
}
}
#endregion
#region IDataErrorInfo members
string IDataErrorInfo.Error
{
get { return string.Empty; }
}
string IDataErrorInfo.this[string columnName]
{
get
{
StringBuilder errors = new StringBuilder();
if (_ValidationErrors != null && _ValidationErrors.Count() > 0)
{
foreach (ValidationFailure validationError in _ValidationErrors)
{
if (validationError.PropertyName == columnName)
errors.AppendLine(validationError.ErrorMessage);
}
}
return errors.ToString();
}
}
#endregion
}
I have this customer class as follow:
internal class Customer : ObjBase
{
string _CustomerName = string.Empty;
public string CustomerName
{
get { return _CustomerName; }
set
{
if (_CustomerName == value)
return;
_CustomerName = value;
}
}
class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(obj => obj.CustomerName).NotEmpty();
}
}
protected override IValidator GetValidator()
{
return new CustomerValidator();
}
}
I wrote my validator class inside my customer class because I don’t want to ruse it any ware else, I created a constructor and I put my customer rules their so the FluentValidation can call up on customer validator class and execute validation. I created virtual method in the customer class named ( GetValidator() ) to return an instance of the validator to my base class to call the validate method and obtaining the results.
So what I did works fine on the old version but when I upgrade to FluentValidation Ver 10 I’m getting exception on line “ValidationResult results = _Validator.Validate(this);” The message says “cannot convert from 'ObjBase' to 'FluentValidation.IValidationContext'”
So I tried to solve it but I couldn’t do it. Please I need your advice and help.
Thank you
What I have tried:
I tried this
var context = new ValidationContext<object>(entity);
var result = validator.Validate(context);
But doesn't work