public OperationResult AddProductToCart(string userId, int productId, int selectedQuantity) { Product productToAdd = _productRepository.GetProductById(productId); if (selectedQuantity > productToAdd.Quantity) { return(OperationResult.Error("Error! Selected quantity is less than state of the warehouse.")); } if (selectedQuantity <= 0) { return(OperationResult.Error("Error! Selected quantity is too little.")); } var order = GetCartOrRestoreToCart(userId); if (order == null) { order = CreateNewOrder(userId); } var listOfOrderPositions = _orderRepository.GetOrderById(order.OrderId).OrderPositions; var existedProductInOrder = listOfOrderPositions .Where(o => o.ProductId == productId) .SingleOrDefault(); if (existedProductInOrder == null) { OrderPosition orderPosition = new OrderPosition { NameOfProduct = productToAdd.Name, Price = productToAdd.Price, Quantity = selectedQuantity, TotalPrice = selectedQuantity * productToAdd.Price, ProductId = productId, OrderId = order.OrderId }; _orderRepository.AddOrderPosition(orderPosition); } else { existedProductInOrder.Quantity = existedProductInOrder.Quantity + selectedQuantity; existedProductInOrder.TotalPrice = existedProductInOrder.Quantity * existedProductInOrder.Price; } var product = _productRepository.GetProductById(productId); product.Quantity = product.Quantity - selectedQuantity; _productRepository.UpdateProduct(product); _orderRepository.Submit(); return(OperationResult.Success()); }