C# 程序中使用AutoMapper实体映射
我的开发环境framework为4.7.2
- 添加AutoMapper 9.0引用
- 创建实体映射公共类
public class AutoMapperUnity { public static IMapper autoMapperTool; public AutoMapperUnity() { autoMapperTool = AutoMapperUnity.MapperInitialize(); } /// <summary> /// 注册映射关系(只能运行一次) /// </summary> public static IMapper MapperInitialize() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<person, student>(); // cfg.SourceMemberNamingConvention = new PascalCaseNamingConvention();//命名是小写并包含下划线 // cfg.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();//帕斯卡命名规则(每个单词的首字母大写) }); var mapper = config.CreateMapper(); return mapper; } }
- 创建映射实体
public class person { public int id { get; set; } /// <summary> /// 姓名 /// </summary> public string uName { get; set; } /// <summary> /// 年龄 /// </summary> public int uAge { get; set; } /// <summary> /// 爱好 /// </summary> public string hobby { get; set; } }
public class student { /// <summary> /// 姓名 /// </summary> public string uName { get; set; } /// <summary> /// 年龄 /// </summary> public int uAge { get; set; } }
- 测试实体映射
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AutoMapperUnity autoMapper = new AutoMapperUnity(); TestAutoMapper(); Application.Run(new Form2()); } private static void TestAutoMapper() { IMapper mapper = AutoMapperUnity.autoMapperTool; person _per = new person { id = 1, uName = "张三", uAge = 12, hobby = "运动" }; student stu = mapper.Map<student>(_per); Console.WriteLine(JsonConvert.SerializeObject(stu)); Console.ReadLine(); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!