编程语言
首页 > 编程语言> > 首页> C#> FluentValidation检查子集合中的重复实体

首页> C#> FluentValidation检查子集合中的重复实体

作者:互联网

我有一个MainEntity类,它具有SubEntity的集合.以下是当前验证:

public class MainEntityValidator : AbstractValidator<MainEntity>
{
    public MainEntityValidator()
    {
        RuleFor(x => x.SubEntities).SetCollectionValidator(new SubEntityValidator());
    }

    public class SubEntityValidator : AbstractValidator<SubEntity>
    {
        public SubEntityValidator()
        {
            RuleFor(x => x.Field1).NotNull();
            RuleFor(x => x.Field2).NotNull();
        }
    }
}

如何添加验证规则,以便仅唯一的SubEntity对象(基于Field1和Field2)必须位于集合中?

解决方法:

如果您需要将验证规则应用于集合属性,但仍需要访问主模型和(或)整个集合,不仅要验证项目,那么可以选择RuleForEach方法:

var comparer = new SubEntityComparer();

RuleForEach(x => x.SubEntities)
    .Must((model, submodel) => model.SubEntities.Count(xsub => comparer.Equals(xsub, submodel)) == 1) // one match that ReferenceEquals hit
    .WithMessage("The item with values {0}, {1} has duplicates in collection of {2} items",
        (model, submodel) => submodel.Field1,
        (model, submodel) => submodel.Field2,
        (model, submodel) => model.SubEntities.Count); // in validation message generation you can access to current item as well as to main model

如果您仅需要一条错误消息作为您描述的验证规则,则可以将简单的谓词规则应用于集合属性SubEntites:

RuleFor(x => x.SubEntities)
    .Must(coll => coll.Distinct(new SubEntityComparer()).Count() == coll.Count)
    .WithMessage("One or more items in collection of {0} items are duplicates",
        (model, coll) => coll.Count); // has access to collection and to main model

在这两种情况下,我都使用相同的相等比较器,但是您也可以覆盖Equals方法,并使用IEnumerable扩展方法的重载和重载,但不包括EqualityComparer参数.

下面列出的EqualComparer代码:

public class SubEntityComparer : IEqualityComparer<SubEntity>
{
    public bool Equals(SubEntity x, SubEntity y)
    {
        if (x == null ^ y == null)
            return false;

        if (ReferenceEquals(x, y))
            return true;

        // your equality comparison logic goes here:
        return x.Field1 == y.Field1 &&
               x.Field2 == y.Field2;
    }

    public int GetHashCode(SubEntity obj)
    {
        return obj.Field1.GetHashCode() + 37 * obj.Field2.GetHashCode();
    }
}

更新:

在两种实现收集验证的方式中,您仍然可以使用SetCollectionValidator(new SubEntityValidator())独立地使用简单规则来验证每个项目.

标签:c,fluentvalidation
来源: https://codeday.me/bug/20191120/2042889.html