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

前端 未结 1 672
北海茫月
北海茫月 2020-12-01 04:05

These are my classes:

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


        
相关标签:
1条回答
  • 2020-12-01 04:17

    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:

    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:

    var log = new EventLog {
        SystemId = "Skynet",
        UserId = "Lazy",
        Events = Builder<Event>.CreateListOfSize(5).Build().ToList()
    };
    
    var events = Mapper.Map<IEnumerable<EventDTO>>(log);
    
    0 讨论(0)
提交回复
热议问题