예제 #1
0
        public IActionResult AddToCart(int itemId)
        {
            var product = _productServices.GetProductById(itemId);

            if (product != null)
            {
                int userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier).ToString());
                var order  = _orderServices.GetOrderById(userId);
                if (order != null)
                {
                    var orderDetail = _orderServices.GetOrderDetail(order, product);
                    if (orderDetail != null)
                    {
                        orderDetail.Count += 1;
                    }
                    else
                    {
                        _orderServices.AddOrderDetail(new OrderDetail()
                        {
                            OrderId   = order.OrderId,
                            ProductId = product.Id,
                            Price     = product.Item.Price,
                            Count     = 1
                        });
                    }
                }
                else
                {
                    order = new Order()
                    {
                        IsFinaly   = false,
                        CreateDate = DateTime.Now,
                        UserId     = userId
                    };
                    _orderServices.AddOrder(order);
                    _userServices.SaveChanges();
                    _orderServices.AddOrderDetail(new OrderDetail()
                    {
                        OrderId   = order.OrderId,
                        ProductId = product.Id,
                        Price     = product.Item.Price,
                        Count     = 1
                    });
                }

                _userServices.SaveChanges();
            }
            return(RedirectToAction("ShowCart"));
        }