public async Task <string> AddAsync(CartItemDto dto) { if (dto.Quantity <= 0) { dto.Quantity = 1; } var q = _context.Products.Where(p => p.Id == dto.ProductId); var product = await q.FirstOrDefaultAsync(); if (product == null) { throw new KeyNotFoundException($"The product with ID={dto.ProductId} was not found."); } CartItem cartItem = null; Guid x; if (!Guid.TryParse(dto.CartId, out x)) { dto.CartId = Guid.NewGuid().ToString(); } else { cartItem = await _context.CartItems.FirstOrDefaultAsync(c => c.CartId == dto.CartId && c.ProductId == dto.ProductId); } if (cartItem == null) { // create new cartItem = new CartItem { Id = Guid.NewGuid().ToString(), CartId = dto.CartId, ProductId = dto.ProductId, Quantity = dto.Quantity, Created = DateTime.Now }; await _context.CartItems.AddAsync(cartItem); await _context.SaveChangesAsync(); } else { cartItem.Quantity = dto.Quantity; _context.Entry(cartItem).Property("Quantity").IsModified = true; await _context.SaveChangesAsync(); } return(cartItem.CartId); }
public async Task <int> AddAsync(OrderDto orderDto) { Order order = _mapper.Map <Order>(orderDto); // check products before update foreach (OrderDetail detail in order.OrderDetails) { Product product = await _context.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == detail.ProductId); if (product == null) { throw new KeyNotFoundException($"The product with ID={detail.ProductId} was not found."); } } order.HasBeenShipped = false; order.OrderDate = DateTime.Now; // order.PaymentTransactionId = ""; // TO DO await _context.Orders.AddAsync(order); await _context.SaveChangesAsync(); return(order.Id); }