现在我正在创建一个网站,您可以在其中下订单。
我们有 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 中给出错误。
我知道这是一个很长的问题,但它杀死了我,如果你能提供帮助,我将不胜感激。先感谢您