AutoMapper多个源映射到一个Dto

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!");
    }

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

运行有问题的,可以留言

猜你喜欢

转载自www.cnblogs.com/YikaJIA/p/11782911.html