I wrote a simple parent-child scenario and not being able to get it mapped using Automapper. In the following scenario, i am expecting the list of OrderItems to be mapped to list of dtoOrderItems but its not happening automatically. Do i need to write it manually using for loop or something?
public class Order
{
public int OrderNumber {get; set;}
public List<OrderItem> OrderItems { get; set; }
public Order()
{
OrderItems = new List<OrderItem>();
OrderItems.Add(new OrderItem() {Quantity= 10});
}
}
public class OrderItem
{
public int Quantity {get; set;}
}
public class DTOOrder
{
public int DTOOrderNumber { get; set; }
public List<DTOOrderItem> DTOOrderItems { get; set; }
public DTOOrder()
{
DTOOrderItems = new List<DTOOrderItem>();
}
}
public class DTOOrderItem
{
public int DTOQuantity { get; set; }
}
public DTOOrder TestConversion ()
{
AutoMapper.Mapper.CreateMap<OrderItem, DTOOrderItem>();
AutoMapper.Mapper.CreateMap<Order, DTOOrder>();
Order order = new Order();
var dtoOrder = AutoMapper.Mapper.Map<Order, DTOOrder>(order);
return dtoOrder;
}
The reason you don't get collections mapped is: one collection name is OrderItems and another is DTOOrderItems. Automapper maps properties by name (Case sensitive) and cannot resolve this.
To solve this:
1) Rename DTOOrderItems (in your DTO class) to OrderItems
or
2) Override mapping for this property using ForMember method from Automapper API. Something like this:
AutoMapper.Mapper.CreateMap<Order, DTOOrder>()
.ForMember(o => o.OrderItems, dto => dto.DTOOrderItems)
The same issue you will have with Quantity and OrderNumber properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With