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;
        }
    }

修改业务层

        /// <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

上一篇:axios学习


下一篇:一个小技巧解决移动硬盘不能复制文件进去的问题