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

按照這個就可以運行測試 ;目前就不截圖了,還在研究怎么保存圖片

運行有問題的,可以留言


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM