public RedirectToRouteResult Add(int productId, string returnUrl, int quantity=1) { //var cart = new Cart(this.ControllerContext.HttpContext.User.Identity.Name, repository); //Product product = repository.Products.SingleOrDefault(x => x.ProductID == productId); //if (product != null) cart.AddProduct(product, 1); //return RedirectToAction("Index", new {returnUrl}); CartItem cart = repository.CartItems.SingleOrDefault( x => x.Customer.EmailAddress == this.ControllerContext.HttpContext.User.Identity.Name && x.ProductId == productId); if (cart !=null) { cart.Quantity += quantity; repository.Save(cart); } else { var customer =repository.Customers.SingleOrDefault( x => x.EmailAddress == this.ControllerContext.HttpContext.User.Identity.Name); if (customer != null) { cart = new CartItem { ProductId = productId, CustomerId = customer.CustomerID, Quantity = quantity }; repository.Save(cart); } } return RedirectToAction("Index", new {returnUrl}); }
public void AddProduct(Product product, int quantity) { CartItem cartItem = repository.CartItems.FirstOrDefault(x => x.CustomerId == customerId && x.ProductId == product.ProductID);// cartItem = _cart.FirstOrDefault(x => x.Product.ProductID == product.ProductID); if (cartItem != null) { cartItem.Quantity += quantity; } else { cartItem = new CartItem { Quantity = quantity, CustomerId = customerId , ProductId = product.ProductID}; } repository.Save(cartItem); }