[英]Fluent Validation - How to ensure that a collection Count greater than zero when not null, but can be null
我正在努力弄清楚如何定義一個允許集合屬性為 null 但不為空的規則。 為集合屬性提供 null 是一個有效的用例,但是當提供集合時,集合需要至少有一個條目。 因此:
// 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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.