AutoMapper(ASP.NET MVC)
阿新 • • 發佈:2020-11-25
需求:需要將Employee轉換成DTO
public class Employee { public int Age { get; set; } public int EmployeeNum { get; set; } public string Name { get; set; } public string Sex { get; set; } public string Email { get; set; } } public class EmployeeDTO {public int ID { get; set; } public string Name { get; set; } public string Email { get; set; } }
上面兩個類是基礎,下面需要去做對映。
public class EmployeeProfile : Profile { public EmployeeProfile() { //CreateMap<Employee, EmployeeDTO>(); 如果 Employee 和 DTO中所要對映的屬性是一樣的,就可以這樣寫。//將Employee類中的EmployeeNum 轉換成 DTO中的ID CreateMap<Employee, EmployeeDTO>().ForMember(dest => dest.ID, opt => opt.MapFrom(src => src.EmployeeNum));//有多個的話,可以鏈式去寫 } }
對映好了之後,需要在Application_Start方法中去初始化AutoMapper。
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); Mapper.Initialize(cfg=> { cfg.AddProfile(new EmployeeProfile()); }); }
做好對映之後就可以直接使用了。
public ActionResult Index() { List<Employee> employees = new List<Employee>() { new Employee { Age = 18, Sex = "男", Email = "[email protected]", Name = "vichin", EmployeeNum = 1707107 } }; IList<EmployeeDTO> viewModel = Mapper.Map<IList<Employee>, IList<EmployeeDTO>>(employees); return View(); }
下面是結果: