.Net Core3.0 WebApi 项目框架搭建 十:使用AutoMapper实现模型映射

.Net Core3.0 WebApi 项目框架搭建:目录

 

不使用AutoMapper

Model层的viewmodel文件夹新建UserViewModel.cs

    public class UserViewModel
    {
        /// 
        /// ID
        /// 
        public int UserId { get; set; }

        /// 
        /// 用户名
        /// 
        public string UserName { get; set; }

        /// 
        /// 年龄
        /// 
        public int? Age { get; set; }

        /// 
        /// 生日
        /// 
        public string Birthday { get; set; }


        /// 
        /// 手机
        /// 
        public string Phone { get; set; }

        /// 
        /// 地址
        /// 

        public string Address { get; set; }
    }

IUserServices.cs和 类UserServices.cs中,添加GetUserDetails()方法,返回类型是UserViewModel

    public interface IUserService : IBaseService
    {
        /// 
        /// 获取用户数量
        /// 
        /// 
        Task<int> GetCount();

        /// 
        /// 获取用户详情
        /// 
        /// 
        /// 
        Task GetUserDetails(int id);

    }
        public async Task GetUserDetails(int id)
        {
            var userinfo = await userDal.QueryByID(id);

            if (userinfo != null)
            {
                UserViewModel model = new UserViewModel()
                {
                    UserId = userinfo.UserId,
                    UserName = userinfo.UserName,
                    Address = "北京市xx区xx小区",
                    Age = userinfo.Age,
                    Birthday = "1996-06-26",
                    Phone = "13888888888"

                };
                return model;

            }
            else
            {
                return null;
            }
        }

因为我这边只是写了个demo,实体类字段还不是很多,真正的开发起来肯定有很多个字段,而且这种方法系统会有很多,写起来也很累人,后期维护也不方便,要多一个字段少一个字段,要去每个地方去修改。

什么是AutoMapper

它是一种对象与对象之间的映射器,让AutoMapper有意思的就是在于它提供了一些将类型A映射到类型B这种无聊的实例,只要B遵循AutoMapper已经建立的惯例,那么大多数情况下就可以进行相互映射了。

引入 AutoMapper 的相关包

Services项目中引用Nuget包,AutoMapperAutoMapper.Extensions.Microsoft.DependencyInjectionAutoMapper.Extensions.Microsoft.DependencyInjection,这个是用来配合依赖注入的。

.Net Core3.0 WebApi 项目框架搭建 十:使用AutoMapper实现模型映射_第1张图片

添加映射文件 CustomProfile.cs

 在接口层Blog.Core 中,添加文件夹AutoMapper,然后添加映射配置文件 CustomProfile.cs,用来匹配所有的映射对象关系。

    public class CustomProfile : Profile
    {
        /// 
        /// 配置构造函数,用来创建关系映射
        /// 
        public CustomProfile()
        {
            CreateMap();
        }
    }

Startup中,注入服务

services.AddAutoMapper(typeof(Startup));

修改Service层

修改上边UserServices.cs 中GetUserDetails方法中的赋值,改用AutoMapper,并用构造函数注。

        private readonly IUserRepository userDal;
        private readonly IMapper iMapper;
        public UserService(IBaseRepository baseRepository, IUserRepository userRepository, IMapper IMapper) : base(baseRepository)
        {
            userDal = userRepository;
            iMapper = IMapper;

        }

        public async Task GetUserDetails(int id)
        {
            var userinfo = await userDal.QueryByID(id);

            if (userinfo != null)
            {
                //UserViewModel model = new UserViewModel()
                //{
                //    UserId = userinfo.UserId,
                //    UserName = userinfo.UserName,
                //    Address = "北京市xx区xx小区",
                //    Age = userinfo.Age,
                //    Birthday = "1996-06-26",
                //    Phone = "13888888888"

                //};
                UserViewModel model = iMapper.Map(userinfo);
                model.Address = "北京市xx区xx小区";
                model.Birthday = "1996-06-26";
                model.Phone = "13888888888";
                return model;

            }
            else
            {
                return null;
            }
        }

测试AutoMapper

添加一个接口测试automapper

 

        /// 
        /// 测试automapper
        /// 
        /// 
        [HttpGet]
        public async Task AutoMapper(int id)
        {
            var userinfo = await _userService.GetUserDetails(id);

            return Ok(userinfo);
        }

 

F5运行调试,可以看到断点处已经转换成功了

.Net Core3.0 WebApi 项目框架搭建 十:使用AutoMapper实现模型映射_第2张图片

复杂深拷贝映射

 

 有的小伙伴会问,你这个这个简单,都是相同字段的,那当然很方便啦,要是一个复杂的,比如属性名字不一样的,或者说有子类等嵌入型的咋办?放心,一样是可以的。

 

1、属性名称不一样
   CreateMap()
       .ForMember(d => d.CountyName, o => o.MapFrom(s => s.County))
       .ForMember(d => d.ProvinceName, o => o.MapFrom(s => s.Province));
2、如果是还有子类的复杂类型
CreateMap()
      .ForMember(d => d.County, o => o.MapFrom(s => s.Address.County))
      .ForMember(d => d.Province, o => o.MapFrom(s => s.Address.Province))
      .ForMember(d => d.City, o => o.MapFrom(s => s.Address.City))
      .ForMember(d => d.Street, o => o.MapFrom(s => s.Address.Street))
      ;


   public class Student : Entity
    {
        public string Name { get; private set; }
        public string Email { get; private set; }
        public string Phone { get; private set; }
        public DateTime BirthDate { get; private set; }
        public Address Address { get; private set; }
    }

    public class StudentViewModel
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime BirthDate { get; set; }
        public string Phone { get; set; }
        public string Province { get; set; }
        public string City { get; set; }
        public string County { get; set; }
        public string Street { get; set; }
    }

 

你可能感兴趣的:(.Net Core3.0 WebApi 项目框架搭建 十:使用AutoMapper实现模型映射)