1.引入AutoMapper包
2.新建一个类:MappingProfile,类名自定义,但是必须要继承 Profile类 用于创建映射规则
如图:Student为源数据(我这里是数据库表实体) StudentOutDto为转化后的实体(我这里是查询的返回实体),一模一样的字段名会实现映射 (不区分大小写)我这的第二部分 因为Student表中没有StudentInfo这个字段 所以使用ForMember方法去自定义 比如:可能你的数据库字段名叫StudentName
但是你需要在返回的时候字段名改为SchooStulName 那么就可以使用这种方法
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类中注入服务
//添加AutoMapper服务
var mapperConfig = new MapperConfiguration(e => e.AddProfile(new MappingProfile()));
IMapper mapper=mapperConfig.CreateMapper();
builder.Services.AddSingleton(mapper);
4.控制器中进行构造函数注入 我这查询数据库为了方便直接在控制器写的 实际开发请严格遵循代码规范 在自己的逻辑层写
5.效果:会发现其中的StudentInfo数据库是没有的 这就是上面第二步自定义的作用
点赞收藏
谢谢观看