说到 .NET 中的对象映射框架,大部分人的第一映像就是 AutoMapper ,而 Mapster 相对知道的人较少。但其实 Mapster 是一个高性能的对象映射框架,与 AutoMapper 相比,Mapster 在速度和内存占用方面表现更加优秀,可以在只使用1/3内存的情况下获得4倍的性能提升。
1. 基础类1 2 3 4 5 6 7 8 9 10 public class Student { public string StuName { get ; set ; } public string StuAddress { get ; set ; } } public class Student_DbModel { public string StudentName { get ; set ; } public string StudentAddress { get ; set ; } }
2. Startup.cs 注册全局映射Config,也可以不注册1 2 3 4 5 6 7 8 9 10 11 12 services.AddOdinTypeAdapter(opt => { opt.ForType<ErrorCode_DbModel, ErrorCode_Model>() .Map(dest => dest.ShowMessage, src => src.CodeShowMessage); }); services.AddSingleton<ITypeAdapterMapster>(provider => new TypeAdapterMapster(opt => { opt.ForType<ErrorCode_DbModel, ErrorCode_Model>() .Map(dest => dest.ShowMessage, src => src.CodeShowMessage); }));
3. 使用时获取全局注册Config1 2 3 4 var mapsterConfig = OdinInjectCore.GetService<ITypeAdapterMapster>().GetConfig();var mapsterConfig = services.BuildServiceProvider().GetService<ITypeAdapterMapster>().GetConfig();
4. 获取数据准备映射转换对象1 2 3 List<Student_DbModel> stuDbModels = DbScoped.Sugar.Queryable<Student_DbModel>().ToList(); Student_DbModel stuDbModel = stuDbModels[0 ];
5. 对象映射转换1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 var stu = stuDbModel.OdinTypeAdapterBuilder<Student_DbModel, Student>( OdinInjectCore.GetService<ITypeAdapterMapster>().GetConfig() ); var stu = stuDbModel.OdinTypeAdapterBuilder<Student_DbModel, Student>( opt => { opt.Map(dest => dest.StuName, src => src.StudentName); } ); var stu = stuDbModel.OdinTypeAdapterBuilder<Student_DbModel, Student>( opt => { opt.Map(dest => dest.StuName, src => src.StudentName); opt.Map(dest => dest.StuAddress, src => src.StudentAddress); }, OdinInjectCore.GetService<ITypeAdapterMapster>().GetConfig() );
6. 集合映射转换将 stuDbModels List<ErrorCode_DbModel> 集合映射转换为 stuLst List类型的集合
泛型参数说明:
参数名称 说明 Student_DbModel 映射的源类型 Student 转换的目标类型 List 最终转换后的集合类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 var stuLst = stuDbModels.OdinTypeAdapterBuilder<Student_DbModel, Student, List<Student>>( OdinInjectCore.GetService<ITypeAdapterMapster>().GetConfig() ); var stuLst = stuDbModels.OdinTypeAdapterBuilder<Student_DbModel, Student, List<Student>>( opt => { opt.Map(dest => dest.StuName, src => src.StudentName); } ); var stuLst = stuDbModels.OdinTypeAdapterBuilder<Student_DbModel, Student, List<Student>>( opt => { opt.Map(dest => dest.StuName, src => src.StudentName); opt.Map(dest => dest.StuAddress, src => src.StudentAddress); }, OdinInjectCore.GetService<ITypeAdapterMapster>().GetConfig() );
关于 Mapster 更详细的用法,请参照 Mapster 官网 。
具体封装代码详见 Github