FluentValidation 中的 DependentRules 顺序
Order of DependentRules in FluentValidation
我有这样的模型
public class Command : IRequest<bool>
{
public int Id { get; set; }
public int LabelId { get; set; }
public int UserId { get; set; }
}
和流利的验证器
public class Validator : AbstractValidator<Command>
{
public Validator(DbContext dbContext)
{
RuleFor(q => q.LabelId).GreaterThan(0);
RuleFor(q => q.UserId).GreaterThan(0);
RuleFor(q => q.Id).GreaterThan(0);
RuleFor(t => t.Id).GreaterThan(0).DependentRules(() =>
RuleFor(q => q.Id).SetValidator(new EntityExistsValidator(dbContext)));
}
}
其中 EntityExistsValidator
是自定义的 PropertyValidator
,它调用数据库以检查实体是否存在。
如何仅在应用所有规则且模型有效时才调用此验证器?
示例
Property | Value | `EntityExistsValidator` run
-------------------------------------------------
LabelId | 0 | no
UserId | 0 | no
Id | 0 | no
所以,验证失败时不应该运行。仅当模型有效时。我怎样才能做到这一点?
我的建议是使用 PreValidator class`:
public class Validator : AbstractValidator<Command>
{
private class PreValidator : AbstractValidator<Command>
{
internal PreValidator()
{
RuleFor(q => q.LabelId).GreaterThan(0);
RuleFor(q => q.UserId).GreaterThan(0);
RuleFor(q => q.Id).GreaterThan(0);
}
}
public Validator(DbContext dbContext)
{
RuleFor(x => x)
.SetValidator(new PreValidator())
.DependentRules(() => RuleFor(q => q.Id)
.SetValidator(new EntityExistsValidator(dbContext)));
}
}
我有这样的模型
public class Command : IRequest<bool>
{
public int Id { get; set; }
public int LabelId { get; set; }
public int UserId { get; set; }
}
和流利的验证器
public class Validator : AbstractValidator<Command>
{
public Validator(DbContext dbContext)
{
RuleFor(q => q.LabelId).GreaterThan(0);
RuleFor(q => q.UserId).GreaterThan(0);
RuleFor(q => q.Id).GreaterThan(0);
RuleFor(t => t.Id).GreaterThan(0).DependentRules(() =>
RuleFor(q => q.Id).SetValidator(new EntityExistsValidator(dbContext)));
}
}
其中 EntityExistsValidator
是自定义的 PropertyValidator
,它调用数据库以检查实体是否存在。
如何仅在应用所有规则且模型有效时才调用此验证器?
示例
Property | Value | `EntityExistsValidator` run
-------------------------------------------------
LabelId | 0 | no
UserId | 0 | no
Id | 0 | no
所以,验证失败时不应该运行。仅当模型有效时。我怎样才能做到这一点?
我的建议是使用 PreValidator class`:
public class Validator : AbstractValidator<Command>
{
private class PreValidator : AbstractValidator<Command>
{
internal PreValidator()
{
RuleFor(q => q.LabelId).GreaterThan(0);
RuleFor(q => q.UserId).GreaterThan(0);
RuleFor(q => q.Id).GreaterThan(0);
}
}
public Validator(DbContext dbContext)
{
RuleFor(x => x)
.SetValidator(new PreValidator())
.DependentRules(() => RuleFor(q => q.Id)
.SetValidator(new EntityExistsValidator(dbContext)));
}
}