回顧
前幾篇搬運了AutoMapper的基本用法,自定義映射,相信有看的同學已經會使用AutoMapper這個強大的Mapping工具了。不過細心的你是否還記得前幾篇中有提到Map的創建並非是每次都需要Create,那么AutoMapper對於這些如果管理呢?這篇我們就要來看看AutoMapper的配置。
初始化
AutoMapper提供一個初始化函數(Mapper.Initialize),可以在程序初始化時調用(Web應用程序可以在Global.asax里寫),進行統一的配置初始化。前幾個章節的CreateMap就可以統一寫到此處,如下:
1 Mapper.Initialize(cfg => { 2 Mapper.CreateMap<CalendarEvent, CalendarEventForm>() 3 .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.Date.Date)) 4 .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.Date.Hour)) 5 .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.Date.Minute)); 6 });
OK,是不是很方便,那么問題來了,cfg是個什么東西?這里根本沒用嘛?
當然不是這樣的,Config里的配置還有很多的,只不過這篇我們就講如何統一處理CreateMap,其他配置可以自己敲代碼看一下,如果有問題,也可以留言交流下。后面的章節里會逐個講。
那么本篇就結束了么?沒有,細心的你會不會覺得在Global.asax里寫這么多CreateMap嚴重影響了代碼的美觀和可維護性。如果寫到外面去處理那不是更方便。當然,強大的AutoMapper已經為你想好了,不過顯然這里其實也可以自己單獨寫一個方法來處理。
配置文件 (Profile)
如果熟悉windows的網絡配置netsh wlan profile的同學肯定對Profile的概念不陌生,簡單的說就是按照AutoMapper的規范單獨的制定了一個格式的文件,在該文件中可以預定於一些AutoMapper的配置,用於統一分門別類的管理好我們在使用AutoMapper時需要的配置。
一個標准的AutoMapper配置文件是這樣子的:
1 public class OrganizationProfile : Profile 2 { 3 protected override void Configure() 4 { 5 //將CreateMap放到此處 6 } 7 8 //配置的名稱,默認可以定義為當前的類名 9 public override string ProfileName 10 { 11 get { return this.GetType().Name; } 12 } 13 }
定義好了配置文件,只需要在AutoMapper初始化時添加即可:
1 Mapper.Initialize(cfg => { 2 3 cfg.AddProfile<OrganizationProfile>(); 4 });
如果你覺得配置文件就只有這么簡單的功能的話,那么就錯了,Profile還有更強大的功能,那就是每個Profile里創建的Map可以單獨配置Mapping的一些規則,例如:
public class OrganizationProfile : Profile { protected override void Configure() { //Mapper.CreateMap寫到此處... Etc.. here SourceMemberNamingConvention = new LowerUnderscoreNamingConvention(); DestinationMemberNamingConvention = new PascalCaseNamingConvention(); } }
SourceMemberNamingConvention指的是源對象的屬性匹配規則,即默認的是propertyName -> propertyName的轉換,這里設置了一個帶下划線的匹配LowerUnderscoreNamingConvention, 即property_name -> PropertyName
DestinationMemberNamingConvention指的是目標對象的屬性匹配規則,這里的PascalCaseNamingConvention指的是按照Pascal駝峰命名規則來處理。這兩個處理Convention是AutoMapper已經提供的,如果需要自定義更強大的Convention那么,請期待下節:《AutoMapper搬運工之自定義轉換規則》
以上文章搬運自:https://github.com/AutoMapper/AutoMapper/wiki/Configuration
另外參考文章:http://consultingblogs.emc.com/owainwragg/archive/2010/12/15/automapper-profiles.aspx
如有不對的地方請指教,如果覺得好,請點推薦,感激不盡~