I updated packages in an .NET Framework project developed using FluentValidation v8.1.3. FluentValidation was upgraded to v11.1.0 when I updated the packages in the project. This update caused an error to be thrown by FluentValidation:
public static class Utility
{
public static void Validate(IValidator validator, object entity)
{
/* System.InvalidCastException */
var result = validator.Validate((IValidationContext) validator);
if (result.Errors.Count > 0)
{
throw new ValidationException(result.Errors);
}
}
}
Error details are available below:
System.InvalidCastException: 'Unable to cast object of type 'DevFramework.Business.ValidationRules.FluentValidation.CustomerValidator' to type 'FluentValidation.IValidationContext'.'
How do I fix this problem?
CodePudding user response:
In the current version of FluentValidation v11.1.0 it is necessary to create a ValidationContext
object to fix this error.
public static class Utility
{
public static void Validate(IValidator validator, object entity)
{
/* Notice that the ValidationContext object is created below. */
var context = new ValidationContext<object>(entity);
var result = validator.Validate(context);
if (result.Errors.Count > 0)
{
throw new ValidationException(result.Errors);
}
}
}