FluentValidation具有2个对象之间的映射

问题描述 投票:0回答:1

我有一个清单,所有道具都是一个字符串,我需要维护它。但是现在我想生成一个映射属性的新列表,如果验证失败,它将把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个回答
0
投票

FluentValidation将在验证ValidationResult对象后返回PersonDest

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

converter 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扩展名的递归循环。尝试一下,让我们知道您的生活。

© www.soinside.com 2019 - 2024. All rights reserved.