0

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

我们有 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 的映射总是为空,因此它在 automapper 中给出错误。

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

4

1 回答 1

0

您使用的是旧版本的 Automapper。在 8.0 版本ResolveUsing中与MapFrom. 看起来你已经切换了源和目标。尝试下面的代码或添加.Reversemap()

CreateMap<OrderItem, OrderItemForCreationDto> ()
    .ForMember (dest => dest.TotalPrice, opt => 
    {
        opt.MapFrom (d => d.Item);
        opt.ResolveUsing (d => d.Item.Price * d.Count);
    });
于 2019-03-08T03:04:31.740 回答