AutoMapper
OOM(Object-Object-Mapping
)组件
为了实现实体间的相互转换,从而避免我们每次采用手工的方式进行转换。
使用
- 安装nuget包
install-package AutoMapper
install-package AutoMapper.Extensions.Microsoft.DependencyInjection
AutoMapper.Extensions.Microsoft.DependencyInjection
这个包方便通过依赖注入的方式去使用AutoMapper
- 定义model和viewmodel
namespace Demo.AutoMapperWeb.Model
{
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
}
namespace Demo.AutoMapperWeb.ViewModel
{
public class StudentVM
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
}
- 定义class继承
Profile
创建model和viewModel之间的map关系
namespace Demo.AutoMapperWeb.Mapper
{
public class StudentProfile : Profile
{
/// <summary>
/// 构造函数中实现映射
/// </summary>
public StudentProfile()
{
// Mapping
// 第一次参数是源类型(这里是Model类型),第二个参数是目标类型(这里是DTO类型)
CreateMap<Student, StudentVM>();
}
}
}
ConfigureServices
中添加AddAutoMapper
配置
//自动找到所有继承了Profile的类然后进行配置
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
- 添加controller的AutoMapper注入,并使用AutoMapper实现自动映射
using AutoMapper;
using Demo.AutoMapperWeb.Model;
using Demo.AutoMapperWeb.ViewModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Demo.AutoMapperWeb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
private IMapper _mapper;
public StudentsController(IMapper mapper)
{
this._mapper = mapper;
}
[HttpGet]
public List<StudentVM> Get()
{
List<Student> list = new List<Student>();
for (int i = 0; i < 3; i++)
{
Student student = new Student()
{
ID = i,
Name = $"测试_{i}",
Age = 20,
Gender = "男"
};
list.Add(student);
}
var result = _mapper.Map<List<StudentVM>>(list);
return result;
}
}
}
- 列名不相同时在profile中重新map
双向绑定设置
using AutoMapper;
using Demo.AutoMapperWeb.Model;
using Demo.AutoMapperWeb.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Demo.AutoMapperWeb.Mapper
{
public class StudentProfile : Profile
{
/// <summary>
/// 构造函数中实现映射
/// </summary>
public StudentProfile()
{
// Mapping
// 第一次参数是源类型(这里是Model类型),第二个参数是目标类型(这里是DTO类型)
CreateMap<Student, StudentVM>()
.ForMember(des => des.StudentId, memberOption =>
{
// 列名不相同时 匹配 studentID<=>id
memberOption.MapFrom(map => map.ID);
})
.ForMember(des => des.StudentName, memberOption =>
{
// 列名不相同时 匹配 studentName<=>name
memberOption.MapFrom(map => map.Name);
})
//.ReverseMap() //ReverseMap表示双向映射
;
}
}
}
标签:NetCore,Demo,get,public,应用,AutoMapper,using,AutoMapperWeb
From: https://www.cnblogs.com/thomerson/p/16928346.html