C# 可以使用 AutoMapper 将一个对象映射到对象列表吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18096034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:16:09  来源:igfitidea点击:

Possible to use AutoMapper to map one object to list of objects?

c#automapper

提问by noocyte

These are my classes:

这些是我的课程:

public class EventLog {
        public string SystemId { get; set; }
        public string UserId { get; set; }
        public List<Event> Events { get; set; }
}

public class Event {
        public string EventId { get; set; }
        public string Message { get; set; }
}

public class EventDTO {
        public string SystemId { get; set; }
        public string UserId { get; set; }
        public string EventId { get; set; }
        public string Message { get; set; }
}

Basically I need to go from a single object, with a nested list, to a list of objects with values from the nested list and the parent object. Can this be done in AutoMapper? I realize that I can easily map the Events list and get a list of EventDTO objects and then manually set the SystemId and UserId, it would just be very convenient to let AutoMapper handle it for me.

基本上,我需要从带有嵌套列表的单个对象到带有来自嵌套列表和父对象的值的对象列表。这可以在 AutoMapper 中完成吗?我意识到我可以轻松地映射事件列表并获取 EventDTO 对象列表,然后手动设置 SystemId 和 UserId,让 AutoMapper 为我处理它会非常方便。

采纳答案by Sergey Berezovskiy

You will need these three mapings with one custom converter:

您将需要使用一个自定义转换器的这三个映射:

Mapper.CreateMap<Event, EventDTO>(); // maps message and event id
Mapper.CreateMap<EventLog, EventDTO>(); // maps system id and user id
Mapper.CreateMap<EventLog, IEnumerable<EventDTO>>()
      .ConvertUsing<EventLogConverter>(); // creates collection of dto

Thus you configured mappings from Eventto EventDTOand from EventLogto EventDTOyou can use both of them in custom converter:

因此,您配置了从EventEventDTO和从EventLog到的映射,EventDTO您可以在自定义转换器中同时使用它们:

class EventLogConverter : ITypeConverter<EventLog, IEnumerable<EventDTO>>
{
    public IEnumerable<EventDTO> Convert(ResolutionContext context)
    {
        EventLog log = (EventLog)context.SourceValue;
        foreach (var dto in log.Events.Select(e => Mapper.Map<EventDTO>(e)))
        {
            Mapper.Map(log, dto); // map system id and user id
            yield return dto;
        }
    }
}

Sample code with NBuilder:

使用NBuilder 的示例代码:

var log = new EventLog {
    SystemId = "Skynet",
    UserId = "Lazy",
    Events = Builder<Event>.CreateListOfSize(5).Build().ToList()
};

var events = Mapper.Map<IEnumerable<EventDTO>>(log);