AutoMapper with auto-incremented values

2019-07-21 09:10发布

问题:

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?

回答1:

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.



回答2:

I use the following method which is much simpler and can be written in a base class or an extension method. The example here uses Generics but can be easily transformed

protected virtual IEnumerable<T> ConvertCsvLines(IEnumerable<TV> lines)
{
    var lineNumber = 0;

    return lines.Select(x =>
    {
        var retVal = Mapper.Map<TV, T>(x);
        retVal.LineNumber = lineNumber++;
        return retVal;
    });
}