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();

        }

 

posted @ 2023-07-18 22:35  低调码农哥!  阅读(222)  评论(0编辑  收藏  举报