我正在尝试将对象列表映射到单个对象,使用嵌套列表。
我有以下类
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; }
}
In my List
我想做完全相反的可能使用AutoMapper映射一个对象到对象列表?
谢谢!
由于您的dto可能包含不同的SystemId
和/或UserId
,因此您必须在创建分组对象之前根据此标准进行分组。像往常一样,如果需要手工从另一种类型的给定实例中提取实例,捕获所有方法在AutoMapper中是.ConvertUsing()
,并采用重载提供ResolutionContext以允许在方法本身中调用Map()
方法。
在给出这个理论介绍之后,让我们来看一些解决你问题的实际代码:
public static class Program
{
public static void Main(string[] args)
{
var dtos = new[] {
new EventDTO { SystemId = "1", UserId = "10", EventId = $"Event {Guid.NewGuid()}", Message = $"Message {Guid.NewGuid()}" },
new EventDTO { SystemId = "1", UserId = "20", EventId = $"Event {Guid.NewGuid()}", Message = $"Message {Guid.NewGuid()}" },
new EventDTO { SystemId = "1", UserId = "30", EventId = $"Event {Guid.NewGuid()}", Message = $"Message {Guid.NewGuid()}" },
new EventDTO { SystemId = "2", UserId = "10", EventId = $"Event {Guid.NewGuid()}", Message = $"Message {Guid.NewGuid()}" },
new EventDTO { SystemId = "2", UserId = "20", EventId = $"Event {Guid.NewGuid()}", Message = $"Message {Guid.NewGuid()}" },
new EventDTO { SystemId = "2", UserId = "30", EventId = $"Event {Guid.NewGuid()}", Message = $"Message {Guid.NewGuid()}" },
};
var config = new MapperConfiguration(conf => conf.AddProfile<EventMappingProfile>());
var mapper = config.CreateMapper();
// Have to ask for list, cause DTOs could differ in SystemId and/or UserId
var logs = mapper.Map<List<EventLog>>(dtos);
// Write result to console
foreach (var log in logs)
foreach (var ev in log.Events)
Console.WriteLine($"{log.SystemId} {log.UserId} {ev.EventId} {ev.Message}");
Console.ReadKey();
}
}
public class EventMappingProfile : Profile
{
public EventMappingProfile()
{
CreateMap<EventDTO, Event>();
CreateMap<IEnumerable<EventDTO>, IEnumerable<EventLog>>()
.ConvertUsing((dtos, _, context) =>
{
return dtos
.GroupBy(dto => (dto.SystemId, dto.UserId))
.Select(group => new EventLog
{
SystemId = group.Key.SystemId,
UserId = group.Key.UserId,
Events = group.Select(context.Mapper.Map<Event>).ToList()
})
.ToList();
});
}
}
您需要设置以下映射:
CreateMap<EventDTO, Event>();
CreateMap<EventDTO, EventLog>();
CreateMap<IEnumerable<EventDTO>, EventLog>()
.ForMember(dest => dest.SystemId, opt => opt.MapFrom(src => src.FirstOrDefault() != null ? src.First().SystemId : ""))
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.FirstOrDefault() != null ? src.First().UserId : ""))
.ForMember(dest => dest.Events, opt => opt.MapFrom(src => src));
并调用以下方法:
var eventLog = Mapper.Map<IEnumerable<EventDTO>, EventLog>(events);