简体   繁体   English

将子属性与父属性进行比较?

[英]Compare child property with parent property?

I have these 2 classes: 我有这两个班:

public class Master
{
    public int? TotalAmount;
    public ICollection<Detail> Details;
}

public class Detail
{
    public int Amount;
}

I'm trying to create a rule so that the details collection's total amount is equal to the master's total amount property. 我正在尝试创建一个规则,以便详细信息集合的总金额等于主人的总金额属性。

I'm trying the following rule but I can't access the master's property: 我正在尝试以下规则,但我无法访问主人的财产:

RuleFor(x => x.Details)
    .Must(coll => coll.Sum(item => item.Amount) == x.TotalAmount)
    .When(x => x.Details != null)
    .When(x => x.TotalAmount.HasValue);

What is the correct way to implement this kind of rule? 实施这种规则的正确方法是什么?

You can just use another overload of Must, like this: 你可以使用Must的另一个重载,如下所示:

RuleFor(x => x.Details)
    .Must((master, details, ctx) => master.TotalAmount == details.Sum(r => r.Amount))            
    .When(x => x.Details != null)
    .When(x => x.TotalAmount.HasValue);

However note that, as already pointed in comments, you should not use validation for consistency checks. 但请注意,正如注释中已指出的那样,您不应使用验证进行一致性检查。 You just have one piece of data (sum of details amount). 你只有一个数据(详细数量总和)。 So why just not do like this: 那么为什么不这样做:

public class Master {
    public int? TotalAmount
    {
        get
        {
            if (Details == null)
                return null;
            return Details.Sum(c => c.Amount);
        }
    }

    public ICollection<Detail> Details;
}

The best way I have found to achieve this type of validation is to use a custom validator method like the following: 我发现实现此类验证的最佳方法是使用自定义验证器方法,如下所示:

public class Validator : AbstractValidator<Master>
{
    public Validator()
    {
        RuleFor(master => master)
            .Must(CalculateSumCorrectly)
            .When(master => master.Details != null)
            .When(master => master.TotalAmount.HasValue);
    }

    private bool CalculateSumCorrectly(Master arg)
    {
        return arg.TotalAmount == arg.Details.Sum(detail => detail.Amount);
    }
}

Notice that the rule here is being described as applying to the entire master object; 请注意,此处的规则被描述为应用于整个主对象; RuleFor(master => master) . RuleFor(master => master) This is the trick that allows you to access both properties. 这是允许您访问这两个属性的技巧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM