public async Task <ShoppingCartItems> AddItemToCart(ShoppingCartAddItemDto dto, int userId) { try { var cartList = await _shoppingCartService.GetListWithShoppingCartItems_ShoppingCarts(x => x.User_Id == userId && x.Status && !x.Is_Deleted); var cart = cartList.FirstOrDefault(); var product = await _productService.Get(x => x.Id == dto.productId); if (product.InStock < dto.quantity) { throw new Exception("no stock"); } else { if (cart != null) { var cartItems = cart.ShoppingCartItems; if (cartItems != null && cartItems.Any(x => x.Product_Id == dto.productId)) { var cartProduct = await _shoppingCartItemService.Get(x => x.Product_Id == dto.productId && x.ShoppingCart_Id == cart.Id); cartProduct.Quantity += dto.quantity; if (product.InStock < cartProduct.Quantity) { throw new Exception("no stock"); } return(await _shoppingCartItemService.Update(cartProduct)); } else { var itemCartItem = new ShoppingCartItems() { Product_Id = dto.productId, Quantity = dto.quantity, ShoppingCart_Id = cart.Id, }; return(await _shoppingCartItemService.Add(itemCartItem)); } } else { var itemCart = new ShoppingCarts() { User_Id = userId, Status = true, Is_Deleted = false, }; var newCart = await _shoppingCartService.Add(itemCart); var itemCartItem = new ShoppingCartItems() { Product_Id = dto.productId, Quantity = dto.quantity, ShoppingCart_Id = newCart.Id, }; return(await _shoppingCartItemService.Add(itemCartItem)); } } } catch (Exception) { throw; } }