【问题标题】:FluentValidation with mapping between 2 objectsFluentValidation 与 2 个对象之间的映射
【发布时间】:2020-01-22 18:36:50
【问题描述】:

我有一个需要维护的列表,其中所有道具都是字符串。 但是现在我想生成一个映射属性的新列表,如果验证失败,它会将 PersonSource 的 IsValid 属性设置为 false 并将 ValidationMessage 设置为原因 如果可以将其添加到组合中,我也可以使用 AutoMapper 我的验证类有一堆数据验证,确保有数据并且数据是合适的


 public class PersonSource
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string SomeNumber { get; set; }

        public string BirthDate { get; set; }
        public bool IsValid { get; set; }
        public string ValidationMessage { get; set; }
    }


    public class PersonDest
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int SomeNumber { get; set; }

        public DateTime BirthDate { get; set; }


    }
    public class PersonDestValidator : AbstractValidator<PersonDest>
    {
        public PersonDestValidator()
        {
            RuleFor(x => x.FirstName)
                .NotEmpty()
                .MaximumLength(50);

            RuleFor(x => x.LastName)
                .NotEmpty()
                .MaximumLength(50);

            RuleFor(x => x.BirthDate)
                .LessThan(DateTime.UtcNow);


            RuleFor(x => x.SomeNumber)
                .GreaterThan(0);

        }
    }

【问题讨论】:

  • 你的问题陈述不清楚,我不明白你想达到什么目的

标签: fluentvalidation


【解决方案1】:

FluentValidation 将在您验证您的 PersonDest 对象后返回一个 ValidationResult

要将这个对象映射到一个新的PersonSource 对象,丰富了验证结果,我的第一个想法是使用 AutoMapper 并提供一个custom type converter。自定义类型转换器可以采用 ResolutionContext,这是您用于将验证结果导入映射过程的容器。

转换器Convert 方法看起来像这样:

public PersonSource Convert(PersonDest personDest, PersonSource personSource, ResolutionContext context){
    if (personSource == null)
    {
        personSource = new PersonSource();
    }

    if (personDest == null)
    {
        return personSource;
    }

    ... PersonDest to PersonSource mapping

    var validationResult = (ValidationResult)context.Items["ValidationResult"]

    personSource.IsValid = validationResult.IsValid

    if (!validationResult.IsValid)
    {
        personSource.ErrorMessage = string.Join(Environment.NewLine, validationResult.Errors.Select(x => x.ErrorMessage))
    }
}

ResolutionContext.Mapper 属性提供对映射器的访问,因此可以在映射配置文件中定义基本的 PersonDest 到 PersonSource 映射并在类型转换器中使用它。您可能会遇到带有 ConvertUsing 扩展名的递归循环。试验一下,让我们知道你的进展。

【讨论】:

    猜你喜欢
    • 2011-07-04
    • 1970-01-01
    • 2017-09-03
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 2023-04-08
    • 2018-04-09
    相关资源
    最近更新 更多