我正在努力弄清楚如何定义一个规则,该规则允许collection属性为null,但不能为空。为collection属性提供null是有效的用例,但是当提供collection时,collection需要至少有一个条目。因此:
// Valid
{
"codes": null
}
// Invalid
{
"codes": []
}
// Valid
{
"codes": ["Pass"]
}
我一直在玩,似乎找不到任何有效的方法:
public class UpdateCodesRequest
{
public IEnumerable<string> Codes { get; set; }
}
public class UpdateCodesRequestValidator : AbstractValidator<UpdateCodesRequest>
{
public UpdateCodesRequestValidator()
{
// none of these will work if Codes is null
RuleFor(x => x.Codes.Count()).GreaterThan(0).When(x => x != null);
RuleFor(x => x.Codes).Must(x => x.Any()).When(x => x != null);
RuleFor(x => x.Codes).Must(x => x != null && x.Any()).When(x => x != null);
}
}
RuleFor(x => x.Codes).Must(x => x == null || x.Any());