netcore 2.2 使用 AutoMapper 实现实体之间映射

一、什么是AutoMapper?

AutoMapper是一个简单的对象映射框架(OOM),将一个对象映射到另一个对象。

二、AutoMapper的好处

以前的时候我们将DTO对象转换为Model对象时,我们必须将每一个属性都手动映射

实体类

    /// <summary>
    /// 用户表
    /// </summary>
    [Table("tb_User")]
    public class TbUser
    {
        /// <summary>
        /// 用户Id
        /// </summary>
        [Key]
        [Column("userId")]
        [StringLength(32)]
        public string UserId { get; set; }
        /// <summary>
        /// 用户名
        /// </summary>
        [Column("userName")]
        [StringLength(20)]
        public string UserName { get; set; }
        /// <summary>
        /// 邮箱
        /// </summary>
        [Column("email")]
        [StringLength(30)]
        public string Email { get; set; }
        /// <summary>
        /// 添加时间
        /// </summary>
        [Column("addTime")]
        [Required]
        public DateTime AddTime { set; get; }
    }

DTO传输对象

    /// <summary>
    /// 用户传输对象
    /// </summary>
    public class UserDto
    { 
        /// <summary>
        /// 用户Id
        /// </summary>
        [StringLength(32, ErrorMessage = "{0}最多{1}个字符"), Display(Name = "用户Id")]
        public string UserId { get; set; }
        /// <summary>
        /// 用户名
        /// </summary>
        [StringLength(20, ErrorMessage = "{0}最多{1}个字符"), Display(Name = "用户名")]
        public string UserName { get; set; }
        /// <summary>
        /// 邮箱
        /// </summary>
        [StringLength(30, ErrorMessage = "{0}最多{1}个字符"), Display(Name = "邮箱")]
        public string Email { get; set; }
    }

业务层

    /// <summary>
    /// 业务处理
    /// </summary>
    public class UserService : IUserService
    {
        private readonly MyDbContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext"></param>
        public UserService(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="dto">实体传输对象</param>
        /// <returns></returns>
        public int Add(UserDto dto)
        {
            var user = new TbUser
            {
                UserId = Guid.NewGuid().ToString("N"),
                Email = dto.Email,
                UserName = dto.UserName,
                AddTime = DateTime.Now
            };
            _dbContext.Add(user);
            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;
            return _dbContext.SaveChanges();
        }
    }

这样情况还可以,属性不是很多,如果属性过多(几十,几百),还需要手动赋值,简直太头疼了,还会导致大量的时间浪费在对象转换中,用AutoMapper,只需要简单的配置就可以完成两个对象之间的属性映射,开发中省去了属性转换的时间,从而提高工作效率。

三、使用AutoMapper

安装引用

通过程序包管理器控制台安装AutoMapper

Install-Package AutoMapper -version 9.0.0

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -version 7.0.0

配置映射关系

创建一个类并继承autoMapper的Profile类

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

注入服务

            //注入AutoMapper服务,Mappings就是自己创建的映射类
            services.AddAutoMapper(typeof(Mappings));

 修改业务层代码

    /// <summary>
    /// 业务处理
    /// </summary>
    public class UserService : IUserService
    {
        private readonly MyDbContext _dbContext;
        /// <summary>
        /// 注入接口
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="mapper"></param>
        public UserService(MyDbContext dbContext,IMapper mapper)
        {
            _dbContext = dbContext;
            _mapper = mapper;
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="dto">实体传输对象</param>
        /// <returns></returns>
        public int Add(UserDto dto)
        {
            var info = _mapper.Map<UserDto, TbUser>(dto);
            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;
            _mapper.Map(dto, user);
            return _dbContext.SaveChanges();
        }
    }

运行测试

netcore 2.2 使用 AutoMapper 实现实体之间映射 

PS:一般在使用AutoMapper转换时dto中字段名称要跟实体对象定义一样才能转换成功。 

netcore 2.2 使用 AutoMapper 实现实体之间映射

上一篇:ADB命令指令控制Android系统的WIFI连接开启/关闭状态


下一篇:axios学习