我有一个数据类层次结构
public class Base
{
// Fields to be validated
}
public class Derived1 : Base
{
// More fields to be validated
}
public class Derived2 : Base
{
// More fields to be validated
}
使用FluentValidation框架验证Derived1和Derived2的适当方法是什么,而不重复Base类字段的规则?
答案 0 :(得分:47)
public class Derived2Validator : AbstractValidator<Derived2>
{
public Derived2Validator()
{
Include(new BaseValidator());
Include(new Derived2Validator());
RuleFor(d => d.Derived1Name).NotNull();
}
}
Derived2Validator
不需要继承BaseValidator
或Derived1Validator
。 Include
方法将包含基本验证器的规则。
答案 1 :(得分:44)
采取的一种方法如下:
public class Base
{
public string BaseName { get; set; }
}
public class Derived1 : Base
{
public string Derived1Name { get; set; }
}
public class BaseValidator<T> : AbstractValidator<T> where T : Base
{
public BaseValidator()
{
RuleFor(b => b.BaseName).NotNull();
}
}
public class Derived1Validator : BaseValidator<Derived1>
{
public Derived1Validator()
{
RuleFor(d => d.Derived1Name).NotNull();
}
}
首先创建基本验证器,使其接受泛型类型参数,并指定泛型类型必须是base
类型。设置基类的一般规则并继续。
对于验证基类子级的任何验证器,您将从baseValidator继承这些验证器,其中T将是您的派生类类型。
答案 2 :(得分:0)
我尝试了Include()方法,但由于.net core中的swagger生成的模型没有显示任何更改,因此没有给出我想要的结果。什么工作是创建一个新类来继承具有基类
的验证器/// <summary>
/// Base Class for entity validator classes that specifies a base validator class
/// </summary>
/// <typeparam name="T">The Type being validated</typeparam>
/// <typeparam name="TBaseClass">The validater assigned to the base type of the type being validated</typeparam>
public abstract class BaseAbstractValidator<T, TBaseClass> : AbstractValidator<T>
where TBaseClass : IEnumerable<IValidationRule>
{
protected BaseAbstractValidator() => AppendRules<TBaseClass>();
/// <summary>
/// Add the set of validation rules
/// </summary>
/// <typeparam name="TValidationRule"></typeparam>
private void AppendRules<TValidationRule>() where TValidationRule : IEnumerable<IValidationRule>
{
var rules = (IEnumerable<IValidationRule>)Activator.CreateInstance<TValidationRule>();
foreach (var rule in rules)
{
AddRule(rule);
}
}
}