点网核心自动映射器orderItems

时间:2019-03-07 23:19:57

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

现在,我正在创建一个可以下订单的网站。

我们有Order,OrderItem和Item。

public class Order
{
    public int Id { get; set; }
    public User User { get; set; }  
    public int? UserId { get; set; }
    public ICollection<OrderItem> OrderItems { get; set; }
    public int TotalPrice { get; set; }
    public string Status { get; set; }
     public DateTime CreatedAt { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    public int ItemId { get; set; }
    public virtual Item Item { get; set; }
    public int Count { get; set; }
    public int OrderId { get; set; }
    public Order Order { get; set; }
    public double TotalPrice { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    public int ItemId { get; set; }
    public Item Item { get; set; }
    public int Count { get; set; }
    public int OrderId { get; set; }
    public Order Order { get; set; }
    public double TotalPrice { get; set; }
}

创建订单后,我将收到:

{
    "orderItems": [
        {
            "itemId": 1,
            "count": 4
        }
    ]
}

并且我已经添加了控制器:

 var userFromRepo = await _repo.GetUser (userId);
 OrderForCreationDto.UserId = userId;
 var order = _mapper.Map<Order> (OrderForCreationDto);
     // userFromRepo.Orders.Add(order);
     _repo.Add (order);

     if (await _repo.SaveAll ()) 
     {
         var OrderToReturn = _mapper.Map<OrderForCreationDto> (order);
        return Ok (OrderToReturn);
     }

以及在自动映射器中:

        CreateMap<Order, OrderForCreationDto> ();
        CreateMap<OrderItemForCreationDto, OrderItem> ()
            .ForMember (dest => dest.TotalPrice, opt => {
                opt.MapFrom (d => d.Item);
                opt.ResolveUsing (d => d.Item.Price * d.Count);
            });

,但OrderItem => item的映射始终为null,因此在automapper中会给出错误。

我知道这是一个漫长的问题,但它杀死了我,如果您能帮助我,我将不胜感激。预先谢谢你

1 个答案:

答案 0 :(得分:0)

您正在使用旧版本的Automapper。在8.0版中,ResolveUsingMapFrom合并在一起。 看起来您已切换了源和目标。在下面尝试代码或添加.Reversemap()

CreateMap<OrderItem, OrderItemForCreationDto> ()
    .ForMember (dest => dest.TotalPrice, opt => 
    {
        opt.MapFrom (d => d.Item);
        opt.ResolveUsing (d => d.Item.Price * d.Count);
    });