C# Fluent Validation-将参数传递给集合验证器

C# Fluent Validation-将参数传递给集合验证器,c#,asp.net-mvc,validation,fluentvalidation,C#,Asp.net Mvc,Validation,Fluentvalidation,我正在使用fluent validation I ASP.NET MVC应用程序,但遇到了一个问题。 这是我的规则: RuleFor(x => x.SimpleList) .SetCollectionValidator(new SimpleListValidator()) .When(x => x.Type == SimpleEnum.SpecificType); 我想将x.Type参数传递给SimpleListValidator,我该如何做?某种扩展方

我正在使用fluent validation I ASP.NET MVC应用程序,但遇到了一个问题。 这是我的规则:

RuleFor(x => x.SimpleList)
       .SetCollectionValidator(new SimpleListValidator())
       .When(x => x.Type == SimpleEnum.SpecificType);
我想将x.Type参数传递给SimpleListValidator,我该如何做?某种扩展方法?应该是这样的:

    RuleFor(x => x.SimpleList)
       .SetCollectionValidator(new SimpleListValidator(x => x.Type))
       .When(x => x.Type == SimpleEnum.SpecificType);

在为属性设置集合验证器之后,您可以忘记一个事实:除了当前正在验证的子模型之外,主模型和
(n-1)
子模型都存在。而且在
SetCollectionValidator
中无法将主模型作为参数传递

因此,您必须使用
RuleForEach
方法,而不是设置集合验证器:

RuleForEach(x => x.SubEntities)
    .Must((model, submodel) => IsValidFirst(submodel, model)) // your rules should go here to be applicable to each collection item
        .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); // for error message building you can access both model and submodel being validated
    .Must((model, submodel) => IsValidSecond(submodel, model)) // yet another rule
        .WithMessage("...")
    .When(model => 
        model.Type == SimpleEnum.SpecificType) // can access to main model only, but it is enough for your purposes
我想,将来应该实现将父模型可能存在的事实告诉子验证器的可能性,但现在有唯一可行的方法,如上所述

更新


您可以创建自定义的
ModelBinder
,将每个子实体的
Parent
属性设置为主实体值,并继续使用
SetCollectionValidator()

这是可能的,您可以这样做:

RuleFor(x => x.SimpleList)
   .SetCollectionValidator(model => new SimpleListValidator(model))
   .When(x => x.Type == SimpleEnum.SpecificType);

在SetCollectionValidator类中,您必须创建一个构造函数,该构造函数接受您的模型作为参数(或者您希望传递给验证器的任何其他内容)。但是请记住,您应该在SimpleListValidator类中保留一个无参数构造函数。

Hi,什么是SimpleListValidator?问题中遗漏了什么?我想没关系。这是我想在列表中应用的某种验证器,但这个“SimpleListValidator”在构造函数中使用一个参数,就是这样。现在我不能通过lambda表达式“x= > x.Type”,而且我不知道如何构建适当的扩展方法,如SETCopeLoalValualActudio。如果我理解正确,SimuleListValueCtor得到1个ARG:Type,如果是这样的话:考虑使用Type(x):新SimuleListValueToor(Type of(x))。它会工作吗?但是x.Type它不是对象的类型,这是类中的一个字段(枚举),它可以是任何其他字段等。x.Name,x.Age..你能粘贴SimpleListValidator吗..太好了,这就是我要找的:)