Fluent Validation - 如何确保集合 Count 在不为 null 时大于零,但可以为 null

Fluent Validation - How to ensure that a collection Count greater than zero when not null, but can be 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());