我有这两个实体:
public class Parent
{
public ICollection<Child> Children {get; set;}
}
public class Child
{
public decimal Percentage {get; set;}
}
我想添加验证规则,以便所有孩子的总Percentage
为100.如何在以下验证器中添加此规则?
public ParentValidator()
{
RuleFor(x => x.Children).SetCollectionValidator(new ChildValidator());
}
private class ChildValidator : AbstractValidator<Child>
{
public ChildValidator()
{
RuleFor(x => x.Percentage).GreaterThan(0));
}
}
答案 0 :(得分:3)
对集合属性使用谓词验证器:
public class ParentValidator : AbstractValidator<Parent>
{
public ParentValidator()
{
RuleFor(x => x.Children)
.SetCollectionValidator(new ChildValidator())
.Must(coll => coll.Sum(item => item.Percentage) == 100);
}
}