进入公司后学习到的东西,之前记录在github上 现在搬运过来
AutoMapperDemo
需要安装两个包
- AutoMapper
- AutoMapper.Extensions.Microsoft.DependencyInjection //需要依赖注入AutoMapper,需要下载该包。
在Startup中添加AutoMapper:
public void ConfigureServices(IServiceCollection services)
{
//添加对AutoMapper的支持
services.AddAutoMapper();
}
创建AutoMapper映射规则,新建一个config类,以及两个实体对象, User和UserDto
public class Config:Profile
{
public Config()
{
//CreateMap(typeof(User), typeof(UserDto));
CreateMap<User, UserDto>().
ForMember(dest => dest.Sing,
opt =>
opt.MapFrom(src => src.Sex == 'f' ? "画画" : "打老虎"));
}
}
使用方式.
private IMapper _mapper;
public ValuesController(IMapper mapper)
{
_mapper = mapper;
}
public ActionResult<IEnumerable<UserDto>> Get()
{
List<User> userList = new List<User>()
{
new User() {
Id = 1,
Age = 12,
ClassName = "五年级",
Name = "大大大",
Sex = 'f'
},
new User() {
Id = 2,
Age = 12,
ClassName = "五年级",
Name = "大大大",
Sex = 'f'
},
new User() {
Id = 3,
Age = 12,
ClassName = "五年级",
Name = "大大大",
Sex = 'm'
},
new User() {
Id = 4,
Age = 12,
ClassName = "五年级",
Name = "大大大",
Sex = 'm'
}
};
AutomapperDemo.Model.User user = new User()
{
Id = 1,
Age = 12,
ClassName = "五年级",
Name = "大大大",
Sex = 'f'
};
//var model = _mapper.Map<UserDto>(user);
var model = _mapper.Map<List<UserDto>>(userList);
return model;
}