1.引入AutoMapper包
![在这里插入图片描述](https://img-blog.csdnimg.cn/4bac849b23e3467f87dd0fe3b48d18f2.png)
2.新建一个类:MappingProfile,类名自定义,但是必须要继承 Profile类 用于创建映射规则
如图:Student为源数据(我这里是数据库表实体) StudentOutDto为转化后的实体(我这里是查询的返回实体),一模一样的字段名会实现映射 (不区分大小写)我这的第二部分 因为Student表中没有StudentInfo这个字段 所以使用ForMember方法去自定义 比如:可能你的数据库字段名叫StudentName
但是你需要在返回的时候字段名改为SchooStulName 那么就可以使用这种方法
![在这里插入图片描述](https://img-blog.csdnimg.cn/7f2e24d1d35942df9a0e00d6e0d08bb2.png)
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Student, StudentOutDto>().ForMember(e => e.StudentInfo, e => e.MapFrom(p => p.StudentAge + "-" + p.StudentName + "-" + p.StudentSex));
}
}
3.在Program类中注入服务
![在这里插入图片描述](https://img-blog.csdnimg.cn/635bc23ac71248bfbf1aaa1b012fcb52.png)
var mapperConfig = new MapperConfiguration(e => e.AddProfile(new MappingProfile()));
IMapper mapper=mapperConfig.CreateMapper();
builder.Services.AddSingleton(mapper);
4.控制器中进行构造函数注入 我这查询数据库为了方便直接在控制器写的 实际开发请严格遵循代码规范 在自己的逻辑层写
![在这里插入图片描述](https://img-blog.csdnimg.cn/fb7072bad56c4503b1c69fc2ecc39f66.png)
5.效果:会发现其中的StudentInfo数据库是没有的 这就是上面第二步自定义的作用
![在这里插入图片描述](https://img-blog.csdnimg.cn/bb822ed3257a4b2aa42b8ad3623187bf.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/2b03be7891244e5aacb8ac939c6688f7.png)
点赞收藏
谢谢观看
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)