ASP.NET Core 3.x RESTful API学习记录--AutoMapper简单使用
1. nueget 引用 AutoMapper.Extensions.Microsoft.DependencyInjection
注册 AutoMapper
services.AddAutoMapper(typeof(ServiceProfile));
建 ServiceProfile 类 继承Profile
public class ServiceProfile : Profile { public ServiceProfile() {
CreateMap<User, UserDto>() .ForMember(des=>des.UserName,opt=>opt.MapFrom(src=>src.Name));//如果映射属性名不一致用mapfrom 修改 属性一样去掉ForMember } }
在需要使用的地方注入IMapper
public class UserService{ private IMapper _mapper; public UserService(IMapper mapper){ _mapper=mapper; } public List<UserDto> QueryByName(string userName) { var res = this.queryBll.Query(userName); return _mapper.Map<List<User>, List<UserDto>>(res); } }
知识来源草根专栏 感谢杨旭大佬
更多用法请看官方文档 https://docs.automapper.org/en/stable/