I am just starting to learn C# & ASP.NET MVC framework and I am trying to build a shopping cart functionality. This is my (add to cart method) that I think should work but does not. It adds an item to the cart but whenever I add another item the previous one is gone. Do anyone know why my database saving is not working? Am I using the context the right way?
namespace e_commerse.Controllers
{
public class ShoppingcartController : Controller
{
private ProductDBContext db = new ProductDBContext();
[Authorize]
public ActionResult addToCart(int ID)
{
Product product = db.Products.Find(ID);
if (product == null)
{
return HttpNotFound();
}
var userId = User.Identity.GetUserId();
IEnumerable<ShoppingCart> shoppingcarts =
from cart in db.Shoppingcarts
where cart.userID == userId
select cart;
if (!shoppingcarts.Any())
{
var newShoppingcart = new ShoppingCart();
newShoppingcart.products = new List<Product>();
newShoppingcart.products.Add(product);
newShoppingcart.userID = userId;
db.Shoppingcarts.Add(newShoppingcart);
db.SaveChanges();
return View("Index", newShoppingcart);
}
var shoppingcart = shoppingcarts.First();
if (shoppingcart.products == null)
{
shoppingcart.products = new List<Product>();
}
shoppingcart.products.Add(product);
shoppingcart.userID = userId;
db.SaveChanges();
return View("Index", shoppingcart);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
public class ProductDBContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<ShoppingCart> Shoppingcarts { get; set; }
}
public class ShoppingCart
{
public int ID { get; set; }
public String userID { get; set; }
public List<Product> products { get; set; }
}
public class Product
{
public int ID { get; set; }
public String title { get; set; }
public String description { get; set; }
public decimal price { get; set; }
public String imagepath { get; set; }
public Type type { get; set; }
}
}
Every help is deeply appreciated and excuse my noob code!