AutoMapper 入门

1 使用nuget搜索AutoMapper 然后安装

2 实例代码

    public class AutoMapperTest
    {
        private static IMapper mapper = null;

        /// <summary>
        /// 初始化AutoMapper映射配置
        /// </summary>
        public void AutoMapperInit()
        {
            var config = new MapperConfiguration(cfg => {
                cfg.AddProfile<FooProfile>(); // 直接指定映射关系

                cfg.CreateMap<Foo, FooDto>(); // 使用Profile配置映射关系
            });

            mapper = config.CreateMapper();
        }

        public void Test()
        {
            AutoMapperInit();

            Foo foo = new Foo { ID = 1, Name = "Tom" };

            FooDto dto = mapper.Map<FooDto>(foo);
        }
    }


    #region 使用Profile配置映射关系
    public class FooProfile : Profile
    {
        public FooProfile()
        {
            CreateMap<Foo, FooDto>();
        }
    }
    #endregion


    /// <summary>
    /// 映射前的原对象类型
    /// </summary>
    public class Foo
    {
        public int ID { get; set; }

        public string Name { get; set; }
        public string P1 { get; set; }
    }


    /// <summary>
    /// 映射生成的目标对象类型
    /// </summary>
    public class FooDto
    {
        public int ID { get; set; }

        public string Name { get; set; }
    }

3 测试代码

            AutoMapperTest autoMapperTest = new AutoMapperTest();
            autoMapperTest.Test();

4 运行结果

 

posted @ 2021-03-05 14:52  温故纳新  阅读(112)  评论(0编辑  收藏  举报