Automapper无法填充子对象(v.6.1.1)

时间:2017-07-11 22:45:59

标签: asp.net-core automapper dataobjects.net

我有这个带有2个复杂嵌套对象的主类

public class OrderData
{
    public OrderDO OrderDO { get; set; }
    public CustomerDO CustomerDO { get; set; 

}

我的OrderDO班级

public class OrderDO
    {
        public OrderDO()
        {
            OrderItemDOList = new List<OrderItemDO>();
            PaymentLogDOList = new List<PaymentLogDO>();
        }
        public int Id { get; set; }
        ...
        }
    }

和CustomerDO Class

public class CustomerDO
    {
        public CustomerDO()
        {
            OrderDOList = new List<OrderDO>();
        }
        public int Id { get; set; }
        ...
    }

Last OrderItemDO Class

public class OrderItemDO
{
    public int Id { get; set; }
    ...
}

我无法在OrderDO下映射OrderItemDOList和PaymentLogDOList:

OrderDO orderDO = Mapper.Map<OrderMain, OrderDO>(orderMain);

OrderItemDOList和PaymentLogDOList为空。

2 个答案:

答案 0 :(得分:1)

As mapping between complex objects is a simple thing which AutoMapper definitely does well, this leaves the likely cause of the problem as one of the following:

  • The source objects are not populated (lazy loading?)
  • You have not defined mappings between the inner objects

You can check the first item with a breakpoint on your call to Mapper.Map.

While you've not included enough code to determine if it's the second issue, you can most likely find this yourself by testing your mappings: simply run Mapper.AssertConfigurationIsValid(). If AutoMapper doesn't know how to map something you've got, it'll tell you what the problem is in the exception.

答案 1 :(得分:0)

  

我找到了这种方式。子映射类型将使用

ForMember()
声明   方法

喜欢这个:

config.CreateMap<OrderMain, OrderDO>()
    .ForMember(dest => dest.OrderItemDOList, opt => opt.ResolveUsing(fa => fa.OrderItem))
    .ForMember(dest => dest.PaymentLogDOList, opt => opt.ResolveUsing(fa => fa.PaymentLog));

config.CreateMap<OrderDO, OrderMain>()
    .ForMember(dest => dest.OrderItem, opt => opt.ResolveUsing(fa => fa.OrderItemDOList))
    .ForMember(dest => dest.PaymentLog, opt => opt.ResolveUsing(fa => fa.PaymentLogDOList));

config.CreateMap<OrderItemDO, OrderItem>()
    .ForMember(dest => dest.Id, opt => opt.ResolveUsing(fa => fa.Id))
    .ForMember(dest => dest.DisplayName, opt => opt.ResolveUsing(fa => fa.DisplayName));

config.CreateMap<OrderItem, OrderItemDO>()
    .ForMember(dest => dest.Id, opt => opt.ResolveUsing(fa => fa.Id))
    .ForMember(dest => dest.DisplayName, opt => opt.ResolveUsing(fa => fa.DisplayName));

config.CreateMap<PaymentLog, PaymentLogDO>()
    .ForMember(dest => dest.Id, opt => opt.ResolveUsing(fa => fa.Id))
    .ForMember(dest => dest.OrderId, opt => opt.ResolveUsing(fa => fa.OrderId));