最近在学习.Net Core,于是也了解到了AutoMapper。
首先要 nuget添加下AutoMapper 我这次装的版本号是6.10的。
第一种方法 是想在Controller中使用的
1.新建个配置类 以便之后初始化AutoMapper
public partial class AutoMapperConfiguration : Profile { public AutoMapperConfiguration() { CreateMap<UserEntity, UserDto>().ForMember(u => u.Status, e => e.MapFrom(s => (UserStatus)s.Status)); CreateMap<UserDto, UserEntity>().ForMember(u => u.Status, e => e.MapFrom(s => (byte)s.Status)); } }
2.在Startup.cs中加一个属性
private MapperConfiguration _mapperConfiguration { get; set; }
3.在Start方法中增加
_mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperConfiguration()); });
4.在ConfigureServices方法中增加
services.AddSingleton(sp => _mapperConfiguration.CreateMapper());
5.就可以在Controller中使用了
private readonly IMapper _mapper; public HomeController(IMapper mapper) { _mapper = mapper; } public IActionResult Index() { UserEntity user = new UserEntity { LoginName = "admin", RealName = "管理员" }; var model = _mapper.Map<UserEntity, UserDto>(user); //实现UserEntity对于UserDto的转换 return View(); }
第二种方法 在Service中使用
public class ServiceBase { public readonly IMapper _mapper; public ServiceBase() { var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperConfiguration()); }); _mapper = mapperConfiguration.CreateMapper(); } public void TestMapper() { List list = new List { new UserEntity { LoginName = "admin", RealName = "管理员" }, new UserEntity { LoginName = "admin", RealName = "管理员" }, }; var resullt = _mapper.Map<List<UserEntity>, List<UserDto>>(list); //实现集合转集合 } }