.Net Core6.0 WebAPI项目框架搭建九:AutoMapper的使用

 完整框架项目源码地址:https://download.csdn.net/download/yigu4011/87788956?spm=1001.2014.3001.5503

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

在Web.Core.Services项目中引用Nuget包,AutoMapper 和 AutoMapper.Extensions.Microsoft.DependencyInjection

.Net Core6.0 WebAPI项目框架搭建九:AutoMapper的使用_第1张图片

在Web.Core.Model下添加Dto文件夹,新建模型StudentDto.cs

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

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

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

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


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

        /// 
        /// 地址
        /// 

        public string Address { get; set; }

    }

 添加映射文件 CustomProfile.cs

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

在program.cs中注入服务:

//注入AutoMapper
builder.Services.AddAutoMapper(typeof(CustomProfile));

在服务层StudentService.cs 中新建GetStudentDetails 方法读取学生详情,改用AutoMapper,并用构造函数注入:

IStudentService中新增接口:

        /// 
        /// 获取学生详情
        /// 
        /// 
        /// 
        Task GetStudentDetails(int id);

StudentService新增方法,将Student对象转化成模型:

private readonly IStudentRepository _studentRepository;
        private readonly IMapper _mapper;
        public StudentService(IBaseRepository baseDal, IStudentRepository studentRepository, IMapper mapper) : base(baseDal)
        {
            _studentRepository = studentRepository;
            _mapper = mapper;
        }

        public async Task GetStudentDetails(int id)
        {
            var student = await _studentRepository.QueryByID(id);
            if (student != null)
            {
                StudentDto dto = _mapper.Map(student);
                dto.Birthday = "1992-3-2";
                dto.Address = "北京市朝阳区北京中路388号";
                dto.Phone = "18969960366";
                return dto;
            }
            else
            {
                return null;
            }
        }

StudentController新增接口测试AutoMapper:

        /// 
        /// 测试Automapper
        /// 
        /// 
        /// 
        [HttpGet]
        public async Task GetStudentDetails(int Id)
        {
            var student = await _studentService.GetStudentDetails(Id);
            if(student == null)
            {
                return NotFound();
            }
            else
            {
                return Ok(student);
            }
        }

运行项目:.Net Core6.0 WebAPI项目框架搭建九:AutoMapper的使用_第2张图片

你可能感兴趣的:(.netcore,.netcore)