AutoMapper可以在所有字段上应用通用/全局格式化程序吗? [英] AutoMapper to apply common/global formatter on all fields?
问题描述
我正在使用AutoMapper 3.2.1
I am using AutoMapper 3.2.1
我只是有一个要求,即我的项目的使用者要我做一些简单的转换-将所有字符串字段都修剪为空白并将null转换为string.empty.
I just got a requirement where the consumers of my project want me to do some simple transformations -- have all string fields trimmed of whitespace and convert null to string.empty.
我该如何在AutoMapper中高效地做到这一点?
How would I do this in AutoMapper in an efficient manner?
例如
public class Person()
{
public string First {get; set;}
public string Middle {get; set; }
public string Last {get; set; }
public DateTime DateOfBirth {get; set; }
}
public class PersonDto()
{
public string First {get; set;}
public string Second {get; set; }
public string Last {get; set; }
public DateTime DateOfBirth {get; set; }
}
还有我的地图示例:
Mapper.CreateMap<Person, PersonDto>().
.ForMember(dst => dst.Second, opt => opt.MapFrom(src => src.Middle));
Mapper.CreateMap<PersonDto, Person>().
.ForMember(dst => dst.Last, opt => opt.MapFrom(src => src.Second));
我尝试通过google找到答案,发现有人在使用:
I tried google to find an answer, saw that some people were using:
Mapper.ForSourceType<string>().AddFormatter(MyCustomStringFormatter)
但是AddFormatter似乎已经过时了吗?
but it seems AddFormatter is obsolete?
推荐答案
如果您确实想将这些规则应用于 all 字符串,则可以通过 string
转换为 string
:
If you truly want to apply these rules to all strings, you can set up a mapping from string
to string
:
Mapper.CreateMap<string, string>()
.ConvertUsing(str => (str ?? "").Trim());
从一个 string
属性映射到另一个属性时,将遵循此规则.
This rule will be picked up when mapping from one string
property to another.
这篇关于AutoMapper可以在所有字段上应用通用/全局格式化程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!