WebAPI学习(九):AutoMapper的使用

AutoMapper是一种实体转换关系的模型,AutoMapper是一个.NET的对象映射工具。主要作用是进行领域对象与模型(DTO)之间的转换、数据库查询结果映射至实体对象。

  1. 在TEST.API.Services项目中引用Nuget包,AutoMapper

    1

  2. 在Entity中新增StudentDto.cs
    public class StudentDto
    {
        /// <summary>
        /// ID
        /// </summary>
        public int ID { get; set; }
    
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }
    
        /// <summary>
        /// 年龄
        /// </summary>
        public int? Age { get; set; }
    
        /// <summary>
        /// 生日
        /// </summary>
        public string Birthday {  get; set; }
    
        /// <summary>
        /// 手机
        /// </summary>
        public string Phone {  get; set; }
    
        /// <summary>
        /// 地址
        /// </summary>
        public string Address {  get; set; }
    }
  3. 添加映射文件 CustomProfile.cs
    public class CustomProfile : Profile
     {
         /// <summary>
         /// 构造函数
         /// </summary>
         public CustomProfile()
         {
             CreateMap<Student, StudentDto>();
         }
     }
  4. 在program.cs中注入服务:
    //注入AutoMapper
    builder.Services.AddAutoMapper(typeof(CustomProfile));
  5. IStudentService中新增接口:
    /// <summary>
    /// 获取学生详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    Task<StudentDto> GetStudentDetails(int id);
  6. StudentService新增方法,将Student对象转化成模型
    /// <summary>
    /// 测试autoMapper
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<StudentDto> GetStudentDetails(int id)
    {
        var student = await _studentRepository.QueryByID(id);
        if (student != null)
        {
            StudentDto dto = _mapper.Map<StudentDto>(student);
            dto.Birthday = "1992-2-2";
            dto.Address = "测试地址信息";
            dto.Phone = "18888888888";
            return dto;
        }
        else
        {
            return null;
        }
    }
  7. StudentController新增接口测试AutoMapper:
    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> GetStudentDetails(int id)
    {
        var student = await stuService.GetStudentDetails(id);
        if (student == null) 
        {
            return NotFound();
        }
    
        return Ok(student);
    }

    2

     

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容