c# - 如何在 FluentValidation 中重用数据

标签 c# fluentvalidation

例如,我有两个验证规则的验证器:

// Rule 1
RuleFor(o => o.Email).Must((email) => this.GetDataDataFromDB(email) != 0)
    .WithMessage("User with provided Email was not found in database!");

// Rule 2
RuleFor(o => o.Email).Must((email) => this.GetDataDataFromDB(email) >= 1)
    .WithMessage("There are multiple users with provided Email in database!");

如您所见,有两次使用相同方法调用数据库。如何调用一次并为其他规则重复使用数据?

显示错误消息时的另一个问题:

RuleFor(o => o.Email).Must((email) => this.GetDataDataFromDB(email) >= 1)
    .WithMessage("There are multiple users with following Email '{0}' in database!",
    (model, email) => { return email; });

有没有更好的方法来显示错误消息,而不是总是编写那些 lambda 表达式来检索属性?就像在某处保存模型然后稍后使用它。

简单易行的解决方案就好了!

最佳答案

对于 #1,恐怕没有办法做到这一点。验证器被设计为无状态的,因此它们可以跨线程重用(事实上,强烈建议您将验证器实例创建为单例,因为它们的实例化成本非常高。MVC 集成默认情况下会这样做)。不要乱用静态字段,因为你会遇到线程问题。

(编辑:在这种特殊的简单情况下,您可以将规则组合到对 Must 的单个调用中,但通常您不能在规则之间共享状态)

对于 #2,这取决于您使用的属性验证器。大多数属性验证器实际上允许您使用 {PropertyValue} 占位符,该值将自动插入。但是,在这种情况下,您使用的是不支持占位符的“必须”验证器 (PredicateValidator)。

我在此处列出了支持自定义占位符的验证器:https://github.com/JeremySkinner/FluentValidation/wiki/c.-Built-In-Validators

关于c# - 如何在 FluentValidation 中重用数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37484742/

相关文章:

c# - Fluent Validation 重载 (Less)GreaterThanOrEqualTo 方法不会呈现相同的结果

c# - 在 FluentValidation 中检查空格

c# - Lightinject 中的 FluentValidation

c# - 如何在 C# 中快速检查两个数据传输对象是否具有相同的属性?

c# - 如何让一个类只有在可序列化的情况下才能实现一个接口(interface)?

c# - 分配不同结果的最佳方式?

c# - 从 LinkBut​​ton 下载时文件损坏

C# .NET 3.5 在使用基本示例时不复制流

c# - Fluent Validation 不接受带有千位分隔符的数字

c# - Fluent Validation - 必须设置 n 个项目中的一个