private void AddCartToUser(string email) { // Check if the user has a cart in cache if (Session["Cart"] != null) { ApplicationDbContext db = new ApplicationDbContext(); var user = db.Users.Where(u => u.Email == email).FirstOrDefault(); Cart currentCart = db.Carts.Include(c => c.User).Where(c => c.UserId == user.Id && c.Status == StatusEnum.PENDING).FirstOrDefault(); List<CartProduct> cachedCartProducts = (List<CartProduct>)Session["Cart"]; // Checks if the user already has a cart if (currentCart != null) { // Add products to existing cart List<CartProduct> cartProducts = db.CartProducts.Where(c => c.CartId == currentCart.CartId).ToList(); foreach (CartProduct cart in cachedCartProducts) { cart.CartId = currentCart.CartId; cart.Product = null; var cartProductToRemove = cartProducts.Where(c => c.ProductId == cart.ProductId).FirstOrDefault(); if (cartProductToRemove != null) { db.CartProducts.Remove(cartProductToRemove); db.SaveChanges(); } db.CartProducts.Add(cart); db.SaveChanges(); } } else { // Create a new cart int latestCartId = db.Carts.Any() ? db.Carts.Max(c => c.CartId) : 1; Cart cart = new Cart() { CartId = latestCartId + 1, UserId = user.Id }; // Add products to the new cart foreach (CartProduct cartProduct in cachedCartProducts) { db.CartProducts.Add(new CartProduct() { Cart = cart, CartId = cart.CartId, ProductId = cartProduct.ProductId, AmountOfProducts = cartProduct.AmountOfProducts }); db.SaveChanges(); } } // Empty the session, because the cart has been stored in database. Session["Cart"] = null; } }
private void AddToUserCart(CartProduct input) { Cart cart = db.Carts.Where(c => c.UserId == user.Id && c.Status == StatusEnum.PENDING).FirstOrDefault(); // Check if the user already has a cart in db if (cart != null && cart.Status == StatusEnum.PENDING) { CartProduct cartProduct = new CartProduct() { CartId = cart.CartId, ProductId = input.ProductId, AmountOfProducts = input.AmountOfProducts }; // Check if the product already exists in the cart if (db.CartProducts.Where(c => c.ProductId == cartProduct.ProductId && c.CartId == cart.CartId).Any()) { db.Entry(cartProduct).State = EntityState.Modified; } else { db.CartProducts.Add(cartProduct); } } else { cart = new Cart() { CartId = db.Carts.Any() ? db.Carts.Max(c => c.CartId) + 1: 1, UserId = user.Id, Status = StatusEnum.PENDING }; CartProduct cartProduct = new CartProduct() { Cart = cart, CartId = cart.CartId, ProductId = input.ProductId, AmountOfProducts = input.AmountOfProducts }; db.Carts.Add(cart); db.CartProducts.Add(cartProduct); } db.SaveChanges(); }