AutoMapper多个源映射到一个Dto

Posted yikajia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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!");
    }

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

运行有问题的,可以留言

以上是关于AutoMapper多个源映射到一个Dto的主要内容,如果未能解决你的问题,请参考以下文章

Automapper 无法在单元测试项目中映射外键属性

[使用Automapper时,我是否也应该展平/映射视图模型的内部objetc?

0.AutoMapper

如何使用 AutoMapper 将 json 请求 dto 中的 OData 枚举字符串映射到实体枚举属性

AutoMapper安装及基本用法

使用 Automapper,将 DTO 映射回实体框架,包括引用的实体