2016-07-18 7 views
3

すべての文字列型プロパティに対して正規化メソッドを使用するいくつかの方法がありますか?例えばすべてのメンバのオートマトン正規化

私は2つのクラスがあります。

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

これはいつでも、それはNormalize()法を適用し、その後、文字列に文字列をマッピングしていることをAutoMapperを伝えます。

TextSourceからTextマッピングのものだけでなく、文字列の変換にも適用されます。