03. 全域設定

AutoMapper可以把物件的對應設定集中在一個設定檔裡面,然後用Profile來做群組分類

用一個簡單的MVC網站來做例子

首先是HomeModel物件

public class HomeModel
{
    public int ModelId { get; set; }
    public string ModelName { get; set; }
}

再來是HomeViewModel物件

public class HomeViewModel
{
    public int ViewModelId { get; set; }
    public string ViewModelName { get; set; }
}

接下來在App_Start裡面新增一個AutoMapperConfig檔案

public class AutoMapperConfig
{
    public static void Configure()
    {
        Mapper.Initialize(x =>
            {
                x.AddProfile<HomeProfile>();
            });
    }

    private class HomeProfile : Profile
    {
        protected override void Configure()
        {
            Mapper.CreateMap<HomeModel, HomeViewModel>()
                .ForMember(dest => dest.ViewModelId, opt => opt.MapFrom(src => src.ModelId))
                .ForMember(dest => dest.ViewModelName, opt => opt.MapFrom(src => src.ModelName));

            Mapper.CreateMap<HomeViewModel, HomeModel>()
                .ForMember(dest => dest.ModelId, opt => opt.MapFrom(src => src.ViewModelId))
                .ForMember(dest => dest.ModelName, opt => opt.MapFrom(src => src.ViewModelName));
        }
    }
}

然後在Global.asax中呼叫就行了

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        AutoMapperConfig.Configure();
    }
}