public void AddToCart(int id) { //Retrive the product from the database ShoppingCartId = GetCartID(); var carItem = _db.ShoppingCartItems.SingleOrDefault( c => c.CartId == ShoppingCartId && c.ProductId == id); if (carItem == null) { //Create new cart item if it's not exist carItem = new CartItem { ItemId = Guid.NewGuid().ToString(), ProductId = id, CartId = ShoppingCartId, Product = _db.Products.SingleOrDefault( p => p.ProductID == id), Quantity = 1, DateCreated = DateTime.Now }; _db.ShoppingCartItems.Add(carItem); } else { //If item exist in the session add one item to it carItem.Quantity++; } _db.SaveChanges(); }
public void AddToCart(int id) { // Retrieve the product from teh database ShoppingCartId = GetCartId(); var cartItem = _db.ShoppingCartItems.SingleOrDefault( c => c.CartId == ShoppingCartId && c.ProductId == id); if (cartItem == null) { // Create a new cart item if no cart item exists cartItem = new CartItem { ItemId = Guid.NewGuid().ToString(), ProductId = id, CartId = ShoppingCartId, Product = _db.Products.SingleOrDefault( p => p.ProductID == id), Quantity = 1, DateCreated = DateTime.Now }; _db.ShoppingCartItems.Add(cartItem); } else { // If the item does exist in the cart, // then add one to the quantity. cartItem.Quantity++; } _db.SaveChanges(); }
public void AddToCart(int id) { ShoppingCartId = GetCartId(); var cartItem = _db.ShoppingCartItems.SingleOrDefault(c => c.CartId == ShoppingCartId && c.ProductId == id); if (cartItem == null) { cartItem = new CartItem { ItemId = Guid.NewGuid().ToString(), CartId = ShoppingCartId, ProductId = id, Product = _db.Products.SingleOrDefault(p => p.ProductID == id), Quantity = 1, DateCreated = DateTime.Now }; _db.ShoppingCartItems.Add(cartItem); } else { cartItem.Quantity++; } _db.SaveChanges(); }