public class Order
{
public int OrderId { get; set; }
public string OrderCode { get; set; }
public IList OrderItems { get; set; }
}
pub
First off, I added a few tweaks to your classes. One was to add constructors that initialize the collections so I could add to them in my test. Second, I don't see why you'd want the OrderDTO.OrderItems to be a loosely-typed ICollection. If you do that, Automapper just assigns the IList to the ICollection (since IList implements ICollection). If you define it as IList, Automapper will see that it knows how to convert from OrderItem to OrderItemDTO and will map each member of the collection.
I also had to add some Ignore()'s since OrderItemDTO doesn't contain IdentifiableCode nor TotalCost (not sure what you wanted to do with those). Finally, the parent/child mapping (OrderItemDTO having a reference to its parent) can be done by a simple foreach loop in the AfterMap(). So here's the mapping I came up with:
Mapper.CreateMap<Order, OrderDTO>()
.ForMember(d => d.IdentifiableCode, o => o.Ignore())
.ForMember(d => d.TotalCost, o => o.Ignore())
.AfterMap((s, d) =>
{
foreach (var l in d.OrderItems)
{
l.Order = d;
}
});
Mapper.CreateMap<OrderItem, OrderItemDTO>();
Mapper.AssertConfigurationIsValid();
And here's the test I used to check things out:
var order = new Order
{
OrderCode = "AAA",
OrderId = 22,
OrderItems = new List<OrderItem>(),
};
order.OrderItems.Add(new OrderItem { ItemCount = 2, Order = order, OrderItemId = 33 });
order.OrderItems.Add(new OrderItem { ItemCount = 1, Order = order, OrderItemId = 99 });
var mapped = Mapper.Map<Order, OrderDTO>(order);