2016-07-18 22 views
3

是否有一种简短的方法在所有字符串类型属性上使用规范化方法?所有成员的自动映射器规范

比如我有两个类:

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);   
    } 

,而不是配置的归一化方法为每个属性的独立是更多钞票做一次所有属性?

回答

2

是的,你可以使用一个custom type converter

Mapper.Initialize(cfg => { 
     cfg.CreateMap<TextSource, Text>(); 
     cfg.CreateMap<string, string>().ConvertUsing(s => s.Normalize()); 
}); 

这告诉AutoMapper,每当它映射一个字符串转换为字符串,然后应用Normalize()方法。

注意,这将适用于所有字符串转换,不只是在TextSourceText映射的人。