流畅的验证 - 如何遍历 List<string>

fluent validation - How to loop through List<string>

这是我的 xml :

  <recordset>
  <!-- multiple value record-->
  <record>
    <KeyName>aliases</KeyName>
    <KeyValue>
      
      <val>VENKAT</val>
      <val>vraja</val>
    </KeyValue>
  </record>


  <!-- single value record-->
  <record>
    <KeyName>accountType</KeyName>
    <KeyValue>

      <val>ADM</val>
    </KeyValue>
  </record>
</recordset>

这是我对 xml.

的等效 c# class
public class Record
{
    public string KeyName { get; set; }
    public KeyValue KeyValue { get; set; }
}

public class Recordset
{
    public List<Record> Record { get; set; }
}

现在我正在使用流畅的验证来验证我的记录集中的每条记录。

SchemaValidator.cs

public class SchemaValidator : AbstractValidator<Entity.EigenData.Recordset>
{
    public SchemaValidator()
    {
        RuleFor(rec => rec.Record[0]).NotNull().SetValidator(new RecordValidator());
    }
}

RecordValidator.cs

public class RecordValidator : AbstractValidator<Entity.EigenData.Record>
{
    public RecordValidator()
    {
        RuleFor(rec => rec.KeyName).NotNull();
        RuleFor(rec => rec.KeyValue).NotNull();
    }
}

注意:我只能验证第一条记录

RuleFor(rec => rec.Record[0]).NotNull().SetValidator(new RecordValidator());

我将如何验证记录集中的所有记录? 我试过 RuleFor(rec => rec.Record).NotNull().SetValidator(new RecordValidator()); 但出现转换错误

Program.cs

 //Note: Recordset contains many List<record>
 private static void Validate(Entity.EigenData.Recordset recordset)
 {
     SchemaValidator validator = new SchemaValidator();

     ValidationResult results = validator.Validate(recordset);

     if (!results.IsValid)
     {
         foreach (var failure in results.Errors)
         {
             Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
         }
     }
     // throw new NotImplementedException();
 }

您可以使用 RuleForEach

来计算
public class SchemaValidator : AbstractValidator<Entity.EigenData.Recordset>
{
    public SchemaValidator()
    {   
        RuleForEach(rec => rec.Record).NotNull().SetValidator(new RecordValidator());
    }
}