【问题标题】:Automapper - Map a single object with array property to N number of Objects based on count of arrayAutomapper - 根据数组的计数将具有数组属性的单个对象映射到 N 个对象
【发布时间】:2019-02-26 19:06:11
【问题描述】:

我正在尝试将包含数组的对象映射到没有数组的对象列表中。例如:

假设我有这个对象:

public class SourceInformation {
    public decimal Id { get; set; }
    public Person[] People { get; set; }
    ...
}

人物类:

public class Person {
    public string First { get; set; }
    public string Last { get; set; }
    public string Middle { get; set; }
}

我想映射到这个对象:

public class Destination {
    public decimal Id { get; set; }
    public string Name { get; set; }
    ...
}

但我想要的是,如果我的 People 属性中有 N 个 Person 对象,我希望在映射 <SourceInformation, Destination> 时返回 N 个 Destination 对象

每个Destination 对象都应具有相关的名称信息,但它们都将具有相同的Id 属性。

如何告诉 Automapper 1 个 SourceInformation 对象映射到 N 个 Destination 对象?

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    想通了。我最终创建了一个自定义转换器和配置文件。

    简介:

    public class MapperProfile : Profile {
        public MapperProfile() {
            CreateMap<SourceInformation, Destination>().ForMember(....);
            CreateMap<SourceInformation, IEnumerable<Destination>>().ConvertUsing<CustomConverter>();
        }
    }
    

    转换器:

    public class CustomConverter : ITypeConverter<SourceInformation, IEnumerable<Destination>> {
        public IEnumerable<Destination> Convert(SourceInformation source, IEnumerable<Destination> destination, ResolutionContext context) {
            var destinations = new List<Destination>();
            foreach (var person in source.People) {
                var destination = context.Mapper.Map<Destination>(source);
                destination.Name = NameUtilStatic.FormatName(person.Name);
                destinations.Add(destination);
            }
            return destinations;
        }
    }
    

    然后只需调用映射器(我使用 DI 注入的映射器),就像说 _mapper.Map&lt;SourceInformation, IEnumerable&lt;Destination&gt;&gt;(source); 一样简单

    您必须先加载您的个人资料。比如:Mapper.Initialize(cfg =&gt; { cfg.AddProfile&lt;MapperProfile&gt;(); });

    更多示例可以在这里找到:https://docs.automapper.org/en/stable/Configuration.html

    【讨论】:

    • 将 source.People 映射到目的地并将 pass 源作为参数更容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    相关资源
    最近更新 更多