C# FluentValidation传递参数
我在几个小时前发现了FluentValidation,我想重写我所有的验证逻辑,这样它将只使用FV 我使用ATM的问题是,我想使用来自输入的数据作为DomainExists()方法的参数。是否有可能或者我必须找到一种绕过FV的方法来实现这一点C# FluentValidation传递参数,c#,validation,fluentvalidation,C#,Validation,Fluentvalidation,我在几个小时前发现了FluentValidation,我想重写我所有的验证逻辑,这样它将只使用FV 我使用ATM的问题是,我想使用来自输入的数据作为DomainExists()方法的参数。是否有可能或者我必须找到一种绕过FV的方法来实现这一点 public QuoteValidator() { // hardcoded because don't know how to pass input string to RuleFor var inputeddom
public QuoteValidator()
{
// hardcoded because don't know how to pass input string to RuleFor
var inputeddomain = "http://google.com";
RuleFor(r => r.Domain).NotEqual(DomainExists(inputeddomain));
}
// checks if inputeddomain is in repository (SQL DB)
private string DomainExists(string inputeddomain)
{
var context = new QuoteDBContext().Quotes;
var output = (from v in context
where v.Domain == inputeddomain
select v.Domain).FirstOrDefault();
if (output != null) { return output; } else { return "Not found"; }
}
多亏了@bpruitt goddard的提示,我才得以成功。这里有一个解决我问题的方法(希望它能帮助别人)
可以使用FluentValidation的
Must
方法从输入对象传入额外数据
RuleFor(r => r.Domain)
.Must((obj, domain) => DomainExists(obj.InputDomain))
.WithErrorCode("MustExist")
.WithMessage("InputDomain must exist");
尽管这会起作用,但不建议检查验证层中是否存在数据库,因为这是验证与验证的比较。相反,这种检查应该在业务层中进行
RuleFor(r => r.Domain)
.Must((obj, domain) => DomainExists(obj.InputDomain))
.WithErrorCode("MustExist")
.WithMessage("InputDomain must exist");