使用 属性 上的总和验证集合
Validate collection using sum on a property
我有这两个实体:
public class Parent
{
public ICollection<Child> Children {get; set;}
}
public class Child
{
public decimal Percentage {get; set;}
}
我想添加一个验证规则,使所有 children 的总数 Percentage
为 100。如何在以下验证器中添加此规则?
public ParentValidator()
{
RuleFor(x => x.Children).SetCollectionValidator(new ChildValidator());
}
private class ChildValidator : AbstractValidator<Child>
{
public ChildValidator()
{
RuleFor(x => x.Percentage).GreaterThan(0));
}
}
为集合使用谓词验证器属性:
public class ParentValidator : AbstractValidator<Parent>
{
public ParentValidator()
{
RuleFor(x => x.Children)
.SetCollectionValidator(new ChildValidator())
.Must(coll => coll.Sum(item => item.Percentage) == 100);
}
}
我有这两个实体:
public class Parent
{
public ICollection<Child> Children {get; set;}
}
public class Child
{
public decimal Percentage {get; set;}
}
我想添加一个验证规则,使所有 children 的总数 Percentage
为 100。如何在以下验证器中添加此规则?
public ParentValidator()
{
RuleFor(x => x.Children).SetCollectionValidator(new ChildValidator());
}
private class ChildValidator : AbstractValidator<Child>
{
public ChildValidator()
{
RuleFor(x => x.Percentage).GreaterThan(0));
}
}
为集合使用谓词验证器属性:
public class ParentValidator : AbstractValidator<Parent>
{
public ParentValidator()
{
RuleFor(x => x.Children)
.SetCollectionValidator(new ChildValidator())
.Must(coll => coll.Sum(item => item.Percentage) == 100);
}
}