Seraph Cheng Seraph Cheng - 2 months ago 21
ASP.NET (C#) Question

AutoMapper with auto-incremented values

public class OrderDTO
{
public string ClientName { get; set; }
public ICollection<OrderDetailDTO> Details { get; set; }
}

public class Order
{
public string ClientName { get; set; }
public ICollection<OrderDetail> Details { get; set; }
}

public class OrderDetailDTO
{
public int Quantity { get; set; }
public string ProductName { get; set; }
}

public class OrderDetail
{
public int OrderId { get; set; }
public int Quantity { get; set; }
public string ProductName { get; set; }
}


Let's say there are 4
OrderDetailDTO
, I want to have the mapped
OrderDetail
instances with auto-incremented integer values. What I am doing now is post-process the mapped instance.

var mappedOrder = Mapper.Map<OrderDTO, Order>(orderDto);
var orderId = 1;
foreach (OrderDetail detail in mappedOrder.Details)
{
detail.OrderId = orderId++;
}


How can I configure the mapping options, so that the mapped
ICollection<OrderDetail>
contains 4
OrderDetail
instances with
OrderId
as 1, 2, 3, 4?

Answer

You could configure AutoMapper to do this with AfterMap:

Mapper.CreateMap<OrderDTO, Order>()
    .AfterMap((src, dest) => 
    {
        int orderId = 1;
        foreach (OrderDetail detail in dest.Details)
        {
            detail.OrderId = orderId++;
        }
    });

I don't think there's really a "cleaner" way to do it using AutoMapper.