gpt4 book ai didi

c# - 设置属性是规则对 FluentValidation 有效

转载 作者:太空宇宙 更新时间:2023-11-03 23:42:25 24 4
gpt4 key购买 nike

我有一个看起来像这样的验证器

public class ImageValidator : AbstractValidator<Image>
{
public ImageValidator()
{
RuleFor(e => e.Name).NotEmpty().Length(1, 255).WithMessage("Name must be between 1 and 255 chars");

RuleFor(e => e.Data).NotNull().WithMessage("Image must have data").When(e => e.Id == 0);

RuleFor(e => e.Height).GreaterThan(0).WithMessage("Image must have a height");

RuleFor(e => e.Width).GreaterThan(0).WithMessage("Image must have a width");
}
}

现在我的单元测试失败了,因为高度和宽度是根据数据中的值填充的。

Data 包含一个创建位图图像的字节数组。如果数据不为空(并且 Id 等于 0,因此它是一个新图像),我可以创建一个位图图像并获取高度和宽度值。更新后,高度和宽度已经填充,数据可能为空,因为它已经存储在数据库中。

如果数据的验证规则在我的验证器中为真,我是否可以填充高度和宽度的值?

在我有支票之前

if (myObject.Data == null) throw new ApplicationException(...

但我认为这是一个验证规则,应该在验证器中,还是我只需要将规则拆分?

最佳答案

当前代码如下所示,请注意 .NotNull() 流畅接口(interface)作用于 RuleFor 的结果。

  RuleFor(e => e.Data)
.NotNull()
.WithMessage("Image must have data")
.When(e => e.Id == 0);

假设您可以这样做:

var rf = RuleFor(e => e.Data)
.CheckNull(p=>{
if(p){
// this is the true branch when data is null don't set height/width}
rf.WithMessage("Image must have data");
.When(e=>e.id==0);
else{
//data is not null set the height and with.
rf(e => e.Height).GreaterThan(0).WithMessage("Image must have a height");
rf(e => e.Width).GreaterThan(0).WithMessage("Image must have a width");
});

为了让您能够执行此操作,新的 CheckNull 例程必须能够采用与今天的 .NotNull() 方法相同的类型。

关于c# - 设置属性是规则对 FluentValidation 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28566139/

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