2009-10-27 196 views
1

我試圖與映射屬性名稱的對象,像這樣:Automapper映射

Property_One -> PropertyOne ... etc 
Sample_Property -> SampleProperty 

是否有更好的方法來做到這一點,而不是每個單獨的屬性映射到另一個?唯一的區別是下劃線。

+0

您可以使用ValueInjecter http://valueinjecter.codeplex.com/documentation輕鬆實現,它將是一個修改過的SameNameType ValueInjection,您只需在查找目標屬性時用string.empty替換「_」 – Omu 2010-05-05 18:44:11

回答

0
public class Source 
{ 
    public string Property_One { get; set; } 
} 

public class Dest 
{ 
    public string PropertyOne { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Mapper.CreateMap<Source, Dest>() 
      .ForMember(dest => dest.PropertyOne, 
         opt => opt.MapFrom(src => src.Property_One)); 

     var source = new Source 
     { 
      Property_One = "property1" 
     }; 

     var destination = Mapper.Map<Source, Dest>(source); 
     Console.WriteLine(destination.PropertyOne); 
    } 
} 
+0

這就是我現在正在做的事情,我需要一種映射它的通用方法。看起來,INamingConvention界面將實現這一點。 – 2009-10-27 12:34:13

5

你需要指定下劃線源側命名約定:

Mapper.Initialize(i => 
{ 
    i.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention(); 
    i.CreateMap<Source, Dest>(); 
}); 

你可以做,在全球範圍(如上圖所示)或每個配置文件,如果只有部分源類型遵循這個命名約定。