public void AddItem(Snack snack, int amount) { var cartItem = _context.CartItems.SingleOrDefault( s => s.Snack.Id == snack.Id && s.CartId == Id); // Create a Cart if necessary, otherwise increase amount if (cartItem == null) { cartItem = new CartItem { CartId = Id, Snack = snack, Amount = amount }; _context.CartItems.Add(cartItem); } else { cartItem.Amount += amount; } _context.SaveChanges(); }
public int RemoveItem(Snack snack) { var cartItem = _context.CartItems.SingleOrDefault( s => s.Snack.Id == snack.Id && s.CartId == Id); var localAmount = 0; if (cartItem != null) { if (cartItem.Amount > 1) { cartItem.Amount--; localAmount = cartItem.Amount; } else { _context.CartItems.Remove(cartItem); } } _context.SaveChanges(); return(localAmount); }