gpt4 book ai didi

c# - Fluent Validation 链式规则不适用于多个 When 条件

转载 作者:行者123 更新时间:2023-12-04 14:53:15 26 4
gpt4 key购买 nike

我有一个非常有趣的行为。我有以下两个测试用例:

[Fact]
public void Ctor_WhenNeverIsTrueAndAfterOcurrenceIsNotNull_HasError()
{
// arrange
var reccurenceEnd = new RecurrenceEnd()
{
IsNever = true,
AfterOccurence = 1
};

// act
var validator = GetValidator();

// assert
validator.ShouldHaveValidationErrorFor(p => p.AfterOccurence, reccurenceEnd);
}

[Fact]
public void Ctor_WhenNeverIsFalseAndAfterOccurenceIsNullAndByDateIsNull_HasError()
{
// arrange
var reccurenceEnd = new RecurrenceEnd()
{
IsNever = false,
AfterOccurence = null,
ByDate = null
};

// act
var validator = GetValidator();

// assert
validator.ShouldHaveValidationErrorFor(p => p.AfterOccurence, reccurenceEnd);
}

在我的验证器上,如果我有以下条件,第一个测试失败,第二个通过。如果我改变规则的顺序,第一个测试通过,第二个失败。
RuleFor(dto => dto.AfterOccurence)
.Cascade(CascadeMode.StopOnFirstFailure)
.Null()
.When(p => p.IsNever == true)
.NotEmpty()
.When(p => p.IsNever == false && p.ByDate == null);

如果我将验证器更改为以下内容,则两个测试都会通过。
RuleFor(dto => dto.AfterOccurence)
.Null()
.When(p => p.IsNever);
RuleFor(dto => dto.AfterOccurence)
.NotEmpty()
.When(p => p.IsNever == false && p.ByDate == null);

我设置错了吗?

最佳答案

好的,从 FluentValidation 的 github-issues 得到了答案:

Hi, this is related to you use of the When condition. By default, a When condition applies to all previous validators in the same RuleFor call, so when you use a single call to RuleFor, you’re essentially doubling up on conditions. You should either use separate calls to RuleFor (as you have in your second example), or use the other overload of When that allows you to specify ApplyConditionTo.CurrentValidator



第二种解决方案是:
RuleFor(dto => dto.AfterOccurence)
.Cascade(CascadeMode.StopOnFirstFailure)
.Null()
.When(p => p.IsNever == true)
.NotEmpty()
.When(p => p.IsNever == false && p.ByDate == null, ApplyConditionTo.CurrentValidator);

关于c# - Fluent Validation 链式规则不适用于多个 When 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52172657/

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