gpt4 book ai didi

c# - FluentValidation 中的 DependentRules 顺序

转载 作者:行者123 更新时间:2023-11-30 22:59:57 25 4
gpt4 key购买 nike

我有这样的模型

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 类:

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)));
}
}

关于c# - FluentValidation 中的 DependentRules 顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com