导包
AutoMapper
AutoMapper.Extensions.Microsoft.DependencyInjection
假如需要将Student映射为StudentCopy
namespace WebApplication14
{
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
public class StudentCopy
{
public string FullName { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
}
新建一个配置类,用于指明映射关系,谁映射到谁
using AutoMapper;
namespace WebApplication14.Profiles
{
public class MapperProfile : Profile
{
public MapperProfile()
{
// source -> target
//CreateMap<Student, StudentCopy>()
//.ForMember非必须,当两个类需要映射的属性名称不一致时可以使用此方法,来指定哪个属性应该映射为哪个属性,例如此处Student.Name需要映射为StudentCopy.FullName
CreateMap<Student, StudentCopy>().ForMember(dest => dest.FullName, option => option.MapFrom(source => source.Name));
}
}
}
在Startup添加AutoMapper服务
services.AddAutoMapper(typeof(Startup));
之后从容器中获取AutoMapper服务并使用即可
例如:_mapper.Map<StudentCopy>(student)
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace WebApplication14.Controllers
{
[ApiController]
[Route("[controller]/[action]")]
public class WeatherForecastController : ControllerBase
{
private readonly IMapper _mapper;
public WeatherForecastController(IMapper mapper)
{
_mapper = mapper;
}
[HttpGet]
public string Test()
{
Student student = new()
{
Name = "张三",
Age = 18,
Sex = "男"
};
var studentCopy = _mapper.Map<StudentCopy>(student);
return JsonConvert.SerializeObject(studentCopy);
}
}
}