how can you validate a base field in an entity framework with fluent validation?

You can inject your db context into validator using the code you provided before. Not sure if there is an adapter that does it automatically

class MyClassValidator : AbstractValidator<MyClass>
{
    public MyClassValidator(MyDbContext dbContext)
    {
        var maxLength = dbContext.Model.FindEntityType(typeof(MyClass))
            .FindProperty(nameof(MyClass.Data)).GetMaxLength();

        RuleFor(x => x.Data)
            .MaximumLength(maxLength.Value);
    }
}

Update

Version that uses expressions

class MyClassValidator : AbstractValidator<MyClass>
{
    public MyClassValidator(MyDbContext dbContext)
    {
        var entityType = dbContext.Model.FindEntityType(typeof(MyClass));

        foreach (var property in typeof(MyClass).GetProperties()
            .Where(x => x.PropertyType == typeof(string)))
        {
            var maxLength = entityType
                .FindProperty(property.Name)
                .GetMaxLength();

            if (maxLength.HasValue) 
            {
                var parameter = Expression.Parameter(typeof(MyClass));
                var memberExpression = Expression.Property(parameter, property.Name);
                var lambdaExpression = Expression.Lambda<Func<MyClass, string>>(memberExpression, parameter);

                RuleFor(lambdaExpression)
                    .MaximumLength(maxLength.Value);
            }
        }

    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top