简体   繁体   中英

How to map a parent/child collection model using 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;
}

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.

You can write these in your extension method ,Instead of looping in every page it remains in a one single page and you will be able to reuse it without duplicate code .

public static List<testMOdel> ToModelList(this List<testEntity> objlist)
        {
            List<testMOdel> list = new List<testMOdel>();
            foreach (var item in objlist)
            {
                list.Add((Mapper.Map<testEntity, testMOdel>(item)));
            }
            return list;
        }
        public static List<testEntity> ToEntityList(this List<testMOdel> modellist)
        {
            List<testEntity> list = new List<testEntity>();
            foreach (var item in modellist)
            {
                list.Add((Mapper.Map<testMOdel, testEntity>(item)));
            }
            return list;
        } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM