C# automapper nested collections
I have a simple model like this one:
public class Order{
public int Id { get; set; }
... ...
public IList<Orde开发者_如何学运维rLine> 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
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();
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.
精彩评论