netcore 2.2 封装 AutoMapper

盛年不重来,一日难再晨,及时当勉励,岁月不待人。这篇文章主要讲述netcore 2.2 封装 AutoMapper相关的知识,希望能为你提供帮助。
在上篇中我们通过创建一个类并继承autoMapper的Profile类

public class Mappings : Profile { public Mappings() { CreateMap< UserDto, TbUser> (); } }

这样做有一种弊端,就是当传输对象很多的时候,还需要手动一个个的配置映射关系,维护起来相对来说也比较麻烦。
封装AutoMapper创建AutoMapperExtension扩展类
/// < summary> /// AutoMapper扩展类 /// < /summary> public static class AutoMapperExtension { /// < summary> /// 将源对象映射到目标对象 /// < /summary> /// < typeparam name="T"> 实体类型< /typeparam> /// < param name="obj"> 源对象< /param> /// < returns> 转化之后的实体< /returns> public static T MapTo< T> (this object obj) { if (obj == null) throw new Exception("异常"); var config = new MapperConfiguration(ctx => ctx.CreateMap(obj.GetType(), typeof(T))); var mapper = config.CreateMapper(); return mapper.Map< T> (obj); }/// < summary> /// 将源对象映射到目标对象 /// < /summary> /// < typeparam name="T"> 实体类型< /typeparam> /// < param name="dto"> 源对象< /param> /// < param name="entity"> 目标对象< /param> /// < returns> 转化之后的实体< /returns> public static T Map< T> (object dto, T entity) { var config = new MapperConfiguration(ctx => ctx.CreateMap(dto.GetType(), typeof(T))); var mapper = config.CreateMapper(); var newModel = mapper.Map(dto, entity); return newModel; } }

修改业务层去掉构造函数中IMapper注入
去掉启动类Startup.cs中  services.AddAutoMapper(typeof(Mappings))  方法
/// < summary> /// 添加用户 /// < /summary> /// < param name="dto"> 实体传输对象< /param> /// < returns> < /returns> public int Add(UserDto dto) { //var info = _mapper.Map< UserDto, TbUser> (dto); var info = dto.MapTo< TbUser> (); info.AddTime = DateTime.Now; info.UserId = Guid.NewGuid().ToString("N"); //var user = new TbUser //{ //UserId = Guid.NewGuid().ToString("N"), //Email = dto.Email, //UserName = dto.UserName, //AddTime = DateTime.Now //}; _dbContext.Add(info); return _dbContext.SaveChanges(); } /// < summary> /// 编辑用户信息 /// < /summary> /// < param name="dto"> 实体传输对象< /param> /// < returns> < /returns> public int Update(UserDto dto) { var user = _dbContext.TbUsers.Find(dto.UserId); if (user == null) throw new Exception("获取用户信息失败"); //user.UserName = dto.UserName; //user.Email = dto.Email; AutoMapperExtension.Map(dto, user); return _dbContext.SaveChanges(); }

运行测试跟封装前一样的效果
【netcore 2.2 封装 AutoMapper】
netcore 2.2 封装 AutoMapper

文章图片


    推荐阅读