.Net Core 中使用AutoMapper进行对象映射
文档:https://automapper.readthedocs.io/en/latest/index.html
GitHub:https://github.com/AutoMapper/AutoMapper/blob/master/docs/index.rst
⒈安装相关依赖
AutoMapper
AutoMapper.Extensions.Microsoft.DependencyInjection
⒉在Startup中添加AutoMapper
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 4 5 //添加对AutoMapper的支持 6 services.AddAutoMapper(cfg => 7 { 8 cfg.AddProfile<AutoMapperConfig>(); 9 }, AppDomain.CurrentDomain.GetAssemblies()); 10 }
⒊使用配置文件创建AutoMapper映射规则
1 using AutoMapper; 2 using AutoMapperTest.Entities; 3 using System; 4 using System.Collections.Generic; 5 using System.Text; 6 7 namespace AutoMapperTest.AutoMapper 8 { 9 public class AutoMapperConfig:Profile 10 { 11 public AutoMapperConfig() 12 { 13 CreateMap<UsersInputDto, Users>().ForMember(d => d.username, u => u.MapFrom(s => s.uname)) //属性名称映射 14 .ForMember(d => d.password, u => u.MapFrom(s => s.pwd)) //属性名称映射 15 .ForMember(d => d.age, u => u.Condition(s => s.age >= 0 && s.age <= 120)) //对一些属性做映射判断 16 .BeforeMap((dto, ent) => ent.fullname = dto.firstname + "_" + dto.lastname) //对一些属性做映射前处理 17 ; 18 } 19 } 20 }
⒋在代码中使用AutoMapper
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 using AutoMapper; 6 using AutoMapperTest.Entities; 7 using Microsoft.AspNetCore.Mvc; 8 9 namespace AutoMapperCore.Controllers 10 { 11 public class UsersController : Controller 12 { 13 private readonly IMapper _mapper; 14 public UsersController(IMapper mapper) 15 { 16 this._mapper = mapper; 17 } 18 public IActionResult Index() 19 { 20 UsersInputDto input = new UsersInputDto() 21 { 22 id = 1, firstname = "fan", lastname = "qi", uname = "fanqisoft", pwd = "admin", enabled = 1 23 }; 24 25 Users users = _mapper.Map<Users>(input); 26 return View(); 27 } 28 } 29 }