使用AutoMapper展平嵌套列表

时间:2015-04-25 23:52:34

标签: c# .net automapper

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

这是我班级结构的片段:

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

我不确定这是不是很简单,我只是在俯视与否。

1 个答案:

答案 0 :(得分:2)

更简单的方法是使用一些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();