AutoMapper是一种实体转换关系的模型,AutoMapper是一个.NET的对象映射工具。主要作用是进行领域对象与模型(DTO)之间的转换、数据库查询结果映射至实体对象。
- 在TEST.API.Services项目中引用Nuget包,AutoMapper
- 在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; } }
- 添加映射文件 CustomProfile.cs
public class CustomProfile : Profile { /// <summary> /// 构造函数 /// </summary> public CustomProfile() { CreateMap<Student, StudentDto>(); } }
- 在program.cs中注入服务:
//注入AutoMapper builder.Services.AddAutoMapper(typeof(CustomProfile));
- IStudentService中新增接口:
/// <summary> /// 获取学生详情 /// </summary> /// <param name="id"></param> /// <returns></returns> Task<StudentDto> GetStudentDetails(int id);
- 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; } }
- 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); }
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容