在AbstractValidator <t>中的FluentValidation期间设置属性值

时间:2018-02-08 06:44:15

标签: c# asp.net-core-webapi fluentvalidation

我使用.net核心Web API创建了一个API端点,用于在我的系统中创建合同。在插入数据之前,我使用FluentValidation验证我的属性。有一种情况,我从API端点获取一个字符串作为输入(即{center:"test center", group:"testGroup", company:"testCompany"})(GUID忽略但如果字符串属性值有效,我将设置针对字符串属性值的GUID([JsonIgnore]属性))并在DB中验证字符串是否存在。如果DB中存在字符串(Center,Group和Company),我必须设置Guids(CenterId,GroupId和CompanyId)而不是DB中的strings属性。说实话,我不知道在AbstractValidator构造函数中使用FluentValidation设置Property值。如果有人知道请分享您的意见。仅供参考我已将表格模式附加到数据中。 enter image description here

    public class Contract
    {
            [JsonIgnore]
            public Guid CenterId { get; set; }
            [JsonIgnore]
            public Guid? CompanyId { get; set; }
            [JsonIgnore]
            public Guid? GroupId { get; set; }

            public string Center { get; set; }

            public string Company { get; set; }

            public string Group { get; set; }
    }

    public class ContractValidator : AbstractValidator<Contract> {
        public ContractValidator(IUsersRepository usersRepository) {
            RuleFor(c => c.Company)
                .MustAsync((command, company) => usersRepository.Exists(command.Company))
                .When(c => c.Company != string.Empty)
                .WithMessage(command => $"Company does not exist");
             RuleFor(c => c.Center)
                .MustAsync((command, center) => usersRepository.Exists(command.Center))
                .When(c => c.Center!= string.Empty)
                .WithMessage(command => $"Center does not exist");
RuleFor(c => c.Group)
                .MustAsync((command, group) => usersRepository.Exists(command.Group))
                .When(c => c.Group!= string.Empty)
                .WithMessage(command => $"Group does not exist");
        }
    }

0 个答案:

没有答案