码迷,mamicode.com
首页 > 移动开发 > 详细

AutoMapper多个源映射到一个Dto

时间:2019-11-03 12:29:13      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:sharp   void   als   pre   ddp   oci   main   esc   world   

AutoMapper多个源映射到一个Dto

首先要引入AutoMapper(我电脑用的8.0,9.0版本)

1. 定义源映射对象

Model如下:

实体Social
    /// <summary>
    /// 社会属性
    /// </summary>
    public class Social
    {
        public int Age { get; set; }
        public bool IsMarried { get; set; }
        public string Name { get; set; }
    }
实体Physical
    /// <summary>
    /// 身体属性
    /// </summary>
    public class Physical
    {
        public string Eye { get; set; }
        public string Mouth { get; set; }
    }
PeopleDto
    public class PeopleDto
    {
        public string Eye { get; set; }
        public string Mouth { get; set; }
        public string Ear { get; set; }
        public int Age { get; set; }
        public bool IsMarried { get; set; }
    }

2. 映射配置

    public class AutoMapperProfile : Profile
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public AutoMapperProfile()
        {
 
            CreateMap<SocialAttribute, PeopleDto>()
                  .ForMember(m => m.Age, n => n.MapFrom(s => s.Age))
                  .ForMember(m => m.IsMarried, n => n.MapFrom(s => s.IsMarried));
            CreateMap<PhysicalAttribute, PeopleDto>()
              .ForMember(m => m.Eye, n => n.MapFrom(s => s.Eye))
              .ForMember(m => m.Mouth, n => n.MapFrom(s => s.Mouth));
        }
    }

3. 控制台的原生注入

    static void Main(string[] args)
    {
        AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<AutoMapperProfile>();
        });
        //DI容器
        var root = new ServiceCollection()                 
            .AddSingleton(config)
              .AddSingleton<IMapper, Mapper>()
              .BuildServiceProvider();
        //容器1
        var provider1 = root.CreateScope().ServiceProvider;   
        var serviceMapper = provider1.GetService<IMapper>();
        //PeopleDto result = new PeopleDto() { Eye = "双眼皮", Mouth = "红润", Age = 18, IsMarried = false };目标
        Physical physical = new Physical() { Eye = "很大很好看", Mouth = "法国兰蔻" };
        Social social = new Social() { Name = "测试name", IsMarried = true, Age = 18 };
        PeopleDto peopleDto = new PeopleDto();
        PeopleDto output = serviceMapper.Map(social, serviceMapper.Map(physical, peopleDto));
        Console.WriteLine("Hello World!");
    }

按照这个就可以运行测试 ;目前就不截图了,还在研究怎么保存图片

运行有问题的,可以留言

AutoMapper多个源映射到一个Dto

标签:sharp   void   als   pre   ddp   oci   main   esc   world   

原文地址:https://www.cnblogs.com/YikaJIA/p/11782911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!