AutoMapper - 将源列表映射到目标数组

AutoMapper - Map source list to a destination array

我正在尝试使用 AutoMapper 将源列表映射到目标数组。

来源类

public class ReservationSource
{
    public Travel TravelSource { get; set; }

    public string SeqNo { get; set; }
}

public class Travel
{
    public string TravelId { get; set; }

    public ICollection<Trip> Trips { get; set; }
}

public class Trip
{
    public string  TrainNumber { get; set; }
    public string  Arrival { get; set; }
}

目的地类

public class ReservationDestination 
{
    public Route[] TravelDest { get; set; }
    public string SeqNumber { get; set; }
}

public class Route
{
    public string SequNumber { get; set; }
    public string RouteId { get; set; }
}

private static route[] GetRoutes(ICollection<Trip> trips)
{
    List<route> routeList = new List<route>();

    foreach (var trip trips)
    {
        var route = new route
        {
            SequNumber = trip.trainNumber

        };
        routeList.Add(route);
    }
    return routeList.ToArray();
}

地图配置

cfg.CreateMap<ReservationSource, ReservationDestination>()

var config = new MapperConfiguration(cfg =>
{
    cfg.AllowNullDestinationValues = true;
    cfg.CreateMap<ReservationSource, ReservationDestination>()
        .ForMember(dest => dest.SeqNumber, o => o.MapFrom(src => SeqNo))
        .ForPath(dest => dest.TravelDest, o => o.MapFrom(src => GetRoutes(src)));
});

这是我尝试过的方法,在这里我想消除 GetRoutes 方法,我将使用 foreach 循环制作手动地图。是否可以使用任何其他方式而不使用循环?

TripRoute 添加映射 类。

cfg.CreateMap<Trip, Route>()
    .ForMember(dest => dest.SequNumber, o => o.MapFrom(src => src.TrainNumber));

Complete Mapping Configuration

var config = new MapperConfiguration(cfg =>
{       
    cfg.CreateMap<Trip, Route>()
        .ForMember(dest => dest.SequNumber, o => o.MapFrom(src => src.TrainNumber));
            
    cfg.AllowNullDestinationValues = true;
    cfg.CreateMap<ReservationSource, ReservationDestination>()
        .ForMember(dest => dest.SeqNumber, o => o.MapFrom(src => src.SeqNo))
        .ForPath(dest => dest.TravelDest, o => o.MapFrom(src => src.TravelSource.Trips));
});

IMapper mapper = config.CreateMapper();
        
var source = new ReservationSource
{
    SeqNo = "Seq001",
    TravelSource = new Travel
    {
        TravelId = "1",
        Trips = new List<Trip>
        {
            new Trip { TrainNumber = "A0001" },
            new Trip { TrainNumber = "B0001" }
        }
    }
};
        
var destination = mapper.Map<ReservationSource, ReservationDestination>(source);
Console.WriteLine(JsonConvert.SerializeObject(destination));

Sample Program

Output

{"TravelDest":[{"SequNumber":"A0001","RouteId":null},{"SequNumber":"B0001","RouteId":null}],"SeqNumber":"Seq001"}

参考资料

Lists and Arrays - AutoMapper documentation