非静态字段需要使用 FluentValidation 返回对象验证 Class

Validation of Class with FluentValidation returning object is required for non-static field

我正在尝试将 FluentValidator 添加到我的 .net core 3.1 Worker Service。我创建了一个 class 来保存我的 CSV 解析文件。

   public partial class Subjects
    {
        public Guid SubjectId { get; set; }
        public string Code { get; set; }
        public Guid OrganizationId { get; set; }
        public string PreferredName { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string Gender { get; set; }
        public string LastNameInitial { get; set; }
        public string CodeDisplay { get; set; }
        public Guid? RaceId { get; set; }
        public Guid? MaritalStatusId { get; set; }
        public Guid? StatusId { get; set; }
        public string Rank { get; set; }
        public string Email { get; set; }
        public string MobilePhone { get; set; }
        public bool MobilePhoneDoNotLeaveMsg { get; set; }
        public bool MobilePhoneDoNotText { get; set; }
        public string WorkPhone { get; set; }
        public bool WorkPhoneDoNotLeaveMsg { get; set; }
    }

然后根据文档,我创建了实现 AbstractValidator 接口的验证 class:

class SubjectsValidation : AbstractValidator<Subjects>
{
    public SubjectsValidation()
    {
        RuleFor(subject => Subjects.FirstName).NotEmpty();
    }
}

根据文档,我需要在构造函数中添加规则。但是,当我为规则传递 lambda 时,我得到了这个错误:

"An object reference is required for non-static field, method, or property"

所以我这样修改了构造函数:

class SubjectsValidation : AbstractValidator<Subjects>
{
    public SubjectsValidation()
    {
        Subjects subject = new Subjects();
        RuleFor(x=>subject.FirstName).NotEmpty();
    }
}

其中出现了错误,但是当我尝试调用验证时,在实例化对象进行测试时出现错误:

Subjects subject = new Subjects();
            subject.FirstName = "John";
            SubjectsValidation validator = SubjectsValidation();

这 return 是一条失败的消息,因为我必须在主题验证中创建一个新主题,所以它 return 失败了。所以按照网站上的说明,我就是无法正常工作。我该如何解决这个问题?

RuleFor 方法需要委托。因此,如果您在正文中使用委托的参数(subject 而不是 Subjects),那么您的第一次尝试将会成功:

class SubjectsValidation : AbstractValidator<Subjects> 
{ 
    public SubjectsValidation()
    { 
        RuleFor(subject => subject.FirstName).NotEmpty(); 
    } 
}