C# automapper nested collections

2019-02-03 01:49发布

问题:

I have a simple model like this one:

public class Order{
   public int Id { get; set; }
   ... ...
   public IList<OrderLine> OrderLines { get; set; }
}

public class OrderLine{
   public int Id { get; set; }
   public Order ParentOrder { get; set; }
   ... ...
}

What I do with Automapper is this:

    Mapper.CreateMap<Order, OrderDto>();
    Mapper.CreateMap<OrderLine, OrderLineDto>();
    Mapper.AssertConfigurationIsValid();

It throw an exception that says: "The property OrderLineDtos in OrderDto is not mapped, add custom mapping ..." As we use a custom syntax in our Domain and in our DomainDto, how I can specify that the collection OrderLineDtos in OrderDto corresponds to OrderLines in Order?

Thank you

回答1:

It works in this way:

    Mapper.CreateMap<Order, OrderDto>()
        .ForMember(dest => dest.OrderLineDtos, opt => opt.MapFrom(src => src.OrderLines));
    Mapper.CreateMap<OrderLine, OrderLineDto>()
        .ForMember(dest => dest.ParentOrderDto, opt => opt.MapFrom(src => src.ParentOrder));
    Mapper.AssertConfigurationIsValid();


回答2:

Nested collections work, as long as the names match up. In your DTOs, you have the name of your collection as "OrderLineDtos", but in the Order object, it's just "OrderLines". If you remove the "Dtos" part of the OrderLineDtos and ParentOrderDto property names, it should all match up.



标签: c# AutoMapper