简体   繁体   English

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

[英]Possible to use AutoMapper to map one object to list of objects?

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? 可以在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. 我意识到,我可以轻松地映射“事件”列表并获取EventDTO对象的列表,然后手动设置SystemId和UserId,让AutoMapper为我处理它非常方便。

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 Event to EventDTO and from EventLog to EventDTO you can use both of them in custom converter: 因此,您配置了从EventEventDTO以及从EventLogEventDTO映射,可以在自定义转换器中使用它们两者:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM