public IActionResult Details(int ID, int quantity = 1) { Guid cartId; Cart cart = null; if (Request.Cookies.ContainsKey("cartId")) { if (Guid.TryParse(Request.Cookies["cartid"], out cartId)) { cart = _donutStoreDbContext.Carts .Include(Carts => Carts.CartItems) .ThenInclude(CartItems => CartItems.Product) .FirstOrDefault(x => x.CookieIdentifier == cartId); } } if (cart == null) { cart = new Cart(); cartId = Guid.NewGuid(); cart.CookieIdentifier = cartId; _donutStoreDbContext.Carts.Add(cart); Response.Cookies.Append("cartId", cartId.ToString(), new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.UtcNow.AddYears(100) }); } CartItem item = cart.CartItems.FirstOrDefault(x => x.Product.ID == ID); if (item == null) { item = new CartItem(); item.Product = _donutStoreDbContext.Products.Find(ID); cart.CartItems.Add(item); } item.Quantity += quantity; cart.LastModified = DateTime.Now; _donutStoreDbContext.SaveChanges(); return(RedirectToAction("Index", "Cart")); }
public IActionResult Remove(int id) { Guid cartId; Cart cart = null; if (Request.Cookies.ContainsKey("cartId")) { if (Guid.TryParse(Request.Cookies["cartId"], out cartId)) { cart = _donutStoreDbContext.Carts .Include(Carts => Carts.CartItems) .ThenInclude(CartItems => CartItems.Product) .FirstOrDefault(x => x.CookieIdentifier == cartId); } } CartItem item = cart.CartItems.FirstOrDefault(x => x.ID == id); cart.LastModified = DateTime.Now; _donutStoreDbContext.CartItems.Remove(item); _donutStoreDbContext.SaveChanges(); return(RedirectToAction("Index")); }
internal static void Initialize(this DonutStoreDbContext db) { db.Database.Migrate(); if (db.Products.Count() == 0) { db.Products.Add(new Product { Name = "Sprinkles Donut", Description = "Homer Simpson Style Donut", Image = "/images/donut1.jpeg", Price = 1.99m }); db.Products.Add(new Product { Name = "Mix and Match", Description = "Various Donuts", Image = "/images/donut3.jpeg", Price = 2.99m }); db.SaveChanges(); } }