Configuration class
- public class AutoMapperWebConfiguration
- {
- public static MapperConfiguration Configure()
- {
- return new MapperConfiguration(cfg =>
- {
- cfg.AddProfile(new MeetingProfile());
- cfg.AddProfile(new ClubProfile());
- });
- }
- }
Profile 範例
相對於使用前直接建 config,套用 Profile 的話,官方建議在其初始化時做 CreateMap()。
- public class ClubProfile : Profile
- {
- public ClubProfile()
- {
- CreateMap<ClubViewModel, Club>();
- CreateMap<Club, ClubViewModel>()
- .ForMember(dest => dest.DisplayText, opt => opt.ResolveUsing(src =>
- {
- if (string.IsNullOrEmpty(src.ChineseAbbr))
- {
- return $"{src.Name}({src.Abbr})";
- }
- else
- {
- return $"{src.ChineseAbbr}({,src.Abbr})";
- }
- }));
- }
- }
以上兩個我是開一個 AutoMapper 資料夾裝一起,不太確定最佳實作應該是怎麼做。
然後在 Global.asax 讓程式跑起來的時候把設定一併帶起來。
- public class MvcApplication : System.Web.HttpApplication
- {
- internal static MapperConfiguration MapperConfig { get; set; }
- protected void Application_Start()
- {
- // skip
- MapperConfig = AutoMapperWebConfiguration.Configure();
- }
- }
在 Controller 就有 mapper 可以建來用了
- public class MeetingsController : Controller
- {
- private IMapper _mapper = MvcApplication.MapperConfig.CreateMapper();
- // GET: Meetings
- public ActionResult Index()
- {
- // skip
- }
- }
ref:SO
沒有留言:
張貼留言