Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 897
S.C. Avatar asked Dec 19 '22 08:12

S.C.


1 Answers

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.

like image 79
Andrew Whitaker Avatar answered Jan 08 '23 00:01

Andrew Whitaker