如何使用 AutoMapper 将信息从一个对象中的一个对象映射到另一个对象

How to use AutoMapper to map info from an object within an object to another object

假设我的 ASP.Net 核心 5 项目中有 3 个对象 类。我正在使用包 AutoMapper.Extensions.Microsoft.DependencyInjection。 类 是:

public class Order 
{
    public int OrderId {get; set;}
    public double OrderPrice{ get; set; }
    public int CustomerId { get; set; }
    public virtual Customer Customer { get; set; }
}

public class Customer 
{
    public int CustomerId { get; set; }
    public string CustomerName{ get; set; }
}

public class OrderODTO 
{
    public int OrderId {get; set;}
    public double OrderPrice{ get; set; }
    public string CustomerName{ get; set; }
}

现在,当我在 Order 和 OrderODTO 之间使用 Automapper 时,OrderId 和 OrderPrice 值将被映射,但是 CustomerName 始终为 null,即使对象 customer 包含在订单对象中也是如此。例如

order 
{
    orderId: 1,
    orderPrice: 3.99,
    customerId: 2,
    customer {
        customerId: 2,
        customerName: "Jack"
   }
}

那么如何使用 Automapper 将订单和客户对象映射到 1 个对象 orderODTO?

您需要在 Order 和 OrderODTO 之间建立映射:

var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderODTO>()
            .ForMember("CustomerName", opt => opt.MapFrom(src => src.Customer.CustomerName)));

使用基于此配置的映射器,您将获得所需的结果

var mapper = new Mapper(config);
        Order order = new Order()
        {
            OrderId = 1,
            OrderPrice = 3.99,
            CustomerId = 2,
            Customer = new Customer() {
                CustomerId = 2,
                CustomerName = "Jack"
            }
        };
OrderODTO orderOdto = mapper.Map<Order, OrderODTO>(order);

结果:

orderOdto 
{
    OrderId: 1,
    OrderPrice: 3.99,
    CustomerName: "Jack"
}