Search code examples
c#fluentvalidation

I am having a problem to use to object with Fluentvalidation


I can not use the object in my code. It says cannot convert from object to FluentValidation.IvalidationContext.

namespace Northwind.Business.Utilities
{
    public static class ValidationTool
    {
        public static void Validate(IValidator validator, object entity)      
        {
            var result = validator.Validate(entity); 
            if (result.Errors.Count > 0)
            {
                throw new ValidationException(result.Errors);
            }
        }


    }
}

Solution

  • The reason why you get the respective error is mentioned in Removal of non-generic Validate overload when you are upgrading to version 9.

    You can resolve it by providing the IValidationContext instance.

    var context = new ValidationContext<object>(model);
    var result = validator.Validate(context); 
    

    Otherwise, you shall consider migrating the validation to IValidator<T> with a generic type instead of IValidator.