流畅验证输出当前记录信息



好的,我正在为我的一个类使用Fluent Validation,我想知道的是。如何确定哪个记录有过错,例如以下内容

被归类为客户可以参考的数字 我将如何使用 Fluent 验证更改下面的字符串,以将其正在处理的文档编号的当前记录输出给客户。

public string DocumentNo { get; set; } 

它就像将其附加到字符串一样简单吗?

法典:

public  class SupplierTransactionsValidation : AbstractValidator<SageStandardImportInvoces>
{ 

public SupplierTransactionsValidation()
{
RuleFor(x => x.AnalysisCode1) // code repeated
.NotEqual("None").WithMessage("Please enter a value for AnalysisCode1")
.Length(0, 3);

RuleFor(x => x.AnalysisCode2) // code repeated
.NotEqual("None").WithMessage("Please enter a value for AnalysisCode2")
.Length(0, 3);
RuleFor(x => x.AnalysisCode3) // code repeated
.NotEqual("None").WithMessage("Please enter a value for AnalysisCode3")
.Length(0, 3);

}
}

如果我正确理解您的问题,您可以创建一个私有方法,该方法通过将表达式的主体强制转换为MemberExpression来获取要验证的属性的名称:

public class SupplierTransactionsValidation : AbstractValidator<SageStandardImportInvoces>
{
public SupplierTransactionsValidation()
{
BuildRule(x => x.AnalysisCode1);
BuildRule(x => x.AnalysisCode2);
BuildRule(x => x.AnalysisCode3);
}
private IRuleBuilderOptions<SageStandardImportInvoces, string> 
BuildRule(System.Linq.Expressions.Expression<Func<SageStandardImportInvoces, string>> expression)
{
return RuleFor(expression)
.NotEqual("None")
.WithMessage($"Please enter a value for {(expression.Body as System.Linq.Expressions.MemberExpression)?.Member.Name}")
.Length(0, 3);
}
}

这样你就不必重复你的逻辑。

最新更新