现在,我正在创建一个可以下订单的网站。
我们有订单,订单和项目。
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);
});
,但始终订购的映射=>项目为空,因此在自动应用程序内给出错误。
我知道这是一个漫长的问题,但它杀死了我,如果您能提供帮助,我将不胜感激。预先感谢
您正在使用旧版本的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);
});