AutoMapper用于嵌套项目集合

时间:2018-06-03 13:37:44

标签: c# automapper

我有以下模型:

public class Order
{
    public long OrderId { get; set; }

    public ICollection<Order_OrderItem> Order_OrderItems { get; set; }
}

public class Order_OrderItem
{
    public long OrderId { get; set; }

    public virtual Order Order { get; set; }

    public int OrderItemId { get; set; }

    public virtual OrderItem OrderItem { get; set; }
}

我在下面创建了DTO:

public class OrderDto
{
    public long OrderId { get; set; }

    public IEnumerable<OrderItemDto> OrderItems { get; set; }
}

如何将Order映射到OrderDto

我在下面遇到错误:

configuration.CreateMap<Order, OrderDto>()
    .ForMember(desc => desc.OrderItems,
        opt => opt.MapFrom(src => src.Order_OrderItems));

我检查了其他相关问题,建议与map属性相关,但我的OrderItems是一个集合属性。我怎么能映射它?

任何帮助都将不胜感激。

更新

更改以下配置:

configuration.CreateMap<Order_OrderItem, OrderItemDto>();
configuration.CreateMap<Order, OrderDto>()
    .ForMember(desc => desc.OrderItems,
        opt => opt.MapFrom(src => src.Order_OrderItems));

检查结果时,OrderItems中的OrderDto将为null

var result = ObjectMapper.Map<OrderDto>(order);

1 个答案:

答案 0 :(得分:1)

OrderItem映射到OrderItemDto

configuration.CreateMap<OrderItem, OrderItemDto>();

Order映射到OrderDto

configuration.CreateMap<Order, OrderDto>()
    .ForMember(dest => dest.OrderItems,
        opt => opt.MapFrom(src => src.Order_OrderItems.Select(o => o.OrderItem)));