具有自动递增值的AutoMapper

具有自动递增值的AutoMapper

本文介绍了具有自动递增值的AutoMapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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; }
}

假设有4个OrderDetailDTO,我想让映射的OrderDetail实例具有自动递增的整数值.我现在正在做的是对映射实例进行后处理.

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++;
}

如何配置映射选项,以使映射的ICollection<OrderDetail>包含4个OrderDetail实例,其中OrderId为1、2、3、4?

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

推荐答案

您可以配置AutoMapper使用AfterMap来做到这一点:

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++;
        }
    });

我认为使用AutoMapper并没有真正的清洁"方法.

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

这篇关于具有自动递增值的AutoMapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:55