Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a parent/child collection model using Automapper?

Tags:

c#

automapper

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;
}
like image 269
user1767363 Avatar asked Oct 23 '12 06:10

user1767363


1 Answers

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.

like image 147
petro.sidlovskyy Avatar answered Nov 04 '22 06:11

petro.sidlovskyy