在所有字符串类型属性上使用规范化方法是否有一些简短的方法?
例如我有两个类:
public class Text
{
public string Header { get; set; }
public string Content { get; set; }
}
public class TextSource
{
public string Header { get; set; }
public string Content { get; set; }
}
我希望他们能够映射:
[TestMethod]
public void ShouldMapTextSourceToText()
{
var TextSource = new TextSource()
{
Content = "<![CDATA[Content]]>",
Header = "<![CDATA[Header]]>",
};
Mapper.Initialize(cfg => cfg.CreateMap<TextSource, Text>()
.ForMember(dest => dest.Content, opt => opt.MapFrom(s => s.Content.Normalize()))
.ForMember(dest => dest.Header, opt => opt.MapFrom(s => s.Header.Normalize())));
var text = Mapper.Map<Text>(TextSource);
Assert.AreEqual("Content", text.Content);
Assert.AreEqual("Header", text.Header);
}
不是单独为每个属性配置规范化方法,而是为所有属性执行一次这样做吗?
答案 0 :(得分:3)
是的,您可以使用custom type converter:
Mapper.Initialize(cfg => {
cfg.CreateMap<TextSource, Text>();
cfg.CreateMap<string, string>().ConvertUsing(s => s.Normalize());
});
这告诉AutoMapper,无论何时将字符串映射到字符串,都应用Normalize()
方法。
请注意,这将适用于所有字符串转换,而不仅仅是TextSource
到Text
映射中的转换。