//TODO: Create check cart function for code efficiency // GET: Orders/ViewCart public ActionResult ViewCart() { string email = User.Identity.GetUserName(); Order cart = db.Orders.FirstOrDefault(i => i.Email == email); if (cart == null) { cart = new Order(); cart.Email = email; cart.Total = 0; cart.OrderDate = DateTime.Now; db.Orders.Add(cart); db.SaveChanges(); } return Redirect("/Orders/Details/" + cart.OrderId); }
// GET: /Order/AddToCart/5 public ActionResult AddToCart(int id, int quantity) { string email = User.Identity.GetUserName(); //find the product Product product = db.Products.First(i => i.ProductId == id); //create a temporary order detail instance based on the provided product id and quantity OrderDetail currentOrder = new OrderDetail(); currentOrder.Quantity = quantity; currentOrder.Total = quantity * product.DiscountedPrice; currentOrder.ProductId = product.ProductId; if(email == null || email == "") { return Redirect("/Account/Register"); } //if the user does not have a cart setup yet, create one //otherwise, update the user's cart Order cart = db.Orders.FirstOrDefault(i => i.Email == email); if (cart == null) { cart = new Order(); cart.Email = email; cart.Total = product.DiscountedPrice * quantity; cart.OrderDate = DateTime.Now; //cart.OrderDetails = new List<OrderDetail>(); //cart.OrderDetails.Add(currentOrder); db.Orders.Add(cart); db.OrderDetails.Add(currentOrder); db.SaveChanges(); } else { //check if the cart has the same item //if it does, update the old order detail //if not, add the current order detail OrderDetail orderDetail = db.OrderDetails .Where(i => i.OrderId == cart.OrderId) .Where(j => j.ProductId == currentOrder.ProductId) .FirstOrDefault(); if(orderDetail == null) { currentOrder.OrderId = cart.OrderId; db.OrderDetails.Add(currentOrder); } else { orderDetail.Quantity += currentOrder.Quantity; orderDetail.Total += currentOrder.Total; db.Entry(orderDetail).State = EntityState.Modified; db.Entry(cart).State = EntityState.Modified; } cart.Total += currentOrder.Total; db.SaveChanges(); } cart = db.Orders.FirstOrDefault(i => i.Email == email); // Go back to the products page return Redirect("/Orders/Details/" + cart.OrderId); }