使用 AutoMapper 展平嵌套列表

Flatten Nested List using AutoMapper

我正在尝试将嵌套对象展平为 .NET 3.5 中的 DTO 对象。到目前为止我看到的大部分内容是使用 AutoMapper 来执行此操作(使用 v1.x 因为我需要使用 .NET 3.5,不幸的是):

这是我的 class 结构的片段:

public class RootObject
{
    [JsonProperty("BaseSupplier")]
    public BaseSupplier BaseSupplier { get; set; }

    [JsonProperty("BaseOrderShipmentLineitem")]
    public IList<BaseOrderShipmentLineitem> BaseOrderShipmentLineitem { get; set; }
}

public class BaseSupplier
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

public class BaseOrderShipmentLineitem
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("qty_delivered")]
    public int QtyDelivered { get; set; }

    [JsonProperty("BaseOrderLineitem")]
    public BaseOrderLineitem BaseOrderLineitem { get; set; }    
}

public class BaseOrderLineitem
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("product_sku")]
    public string ProductSku { get; set; }
}

public class ShipmentDetailsDTO
{
    public int BaseOrderShipmentLineitemId { get; set; }
    public string BaseSupplierName { get; set; }
    public string Sku { get; set; }
}

我一直在尝试这样的事情:

Mapper.CreateMap<BaseOrderLineitem, ShipmentDetailsDTO>()
    .ForMember(d => d.Sku, opts => opts.MapFrom(s => s.ProductSku));
Mapper.CreateMap<BaseOrderShipmentLineitem, ShipmentDetailsDTO>();
Mapper.CreateMap<RootObject, ShipmentDetailsDTO>()
    .ForMember(d => d.Sku, opts => opts.MapFrom(s => Mapper.Map<IEnumerable<BaseOrderLineitem>, IEnumerable<ShipmentDetailsDTO>>(s.BaseOrderShipmentLineitem.SelectMany(q => q.BaseOrderLineitem)).FirstOrDefault().Sku))
    ;

var model = Mapper.Map<IEnumerable<RootObject>, IEnumerable<ShipmentDetailsDTO>>(obj);

使用上面的代码,我在这个位上遇到错误 s.BaseOrderShipmentLineitem.SelectMany(q => q.BaseOrderLineitem):

Cannot implicitly convert type 'IEnumerable<?>' to 'IEnumerable<BaseOrderLineitem>'. An explicit conversion exists (are you missing a cast?)

我不确定这是否是我忽略的简单问题。

一个更简单的方法是使用一些 LINQ 编写一个简单的扩展方法来自己做这个投影。更简单更透明:

public static class MyConversionExtensions
{
    public static IEnumerable<ShipmentDetailsDTO> ToShipmentDetails(this RootObject root)
    {
        return root.BaseOrderShipmentLineitem.Select(x => new ShipmentDetailsDTO() {
            BaseOrderShipmentLineitemId = x.BaseOrderLineitem.Id,
            BaseSupplierName = root.BaseSupplier.Name,
            Sku = x.BaseOrderLineitem.ProductSku
        });
    }
}

用法:

var shipmentDetails = myRootObject.ToShipmentDetails();