FluentValidation with 2 个对象之间的映射



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


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 将在您验证PersonDest对象后返回一个ValidationResult

若要将此对象映射到新的PersonSource对象,并丰富验证结果,我的第一个想法是使用 AutoMap per 并提供自定义类型转换器。自定义类型转换器可以采用一个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扩展名的递归循环。尝试一下,让我们知道您的进展。

最新更新