0

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!

0

3 Answers 3

3

When you fetching ShoppingCart from db it dosen't fetch products list. Your condition is always true:

if (shoppingcart.products == null) // is always true

So ShoppingCart.products is always null, you create new List<Product>() and add one product to it. Thats why you have only one product in ShoppingCart.products list. Because old list is replaced by new with only one item.

You have to load previously saved products befor you add new one. You can use EF lazy-loading. In your example you can add virtual keyword to products property to load it form db when needed:

...
public virtual List<Product> products { get; set; }
Sign up to request clarification or add additional context in comments.

2 Comments

Do not quite understand. could you put the code in some context?
Wow, that worked like a charm! thank you so much!:) And tnx to everyone for helping!
2

I think that problem is with below:

shoppingcart.products.Add(product);
shoppingcart.userID = userId;
db.SaveChanges();

you are adding items to the local variable, not the context. You should change you code to the following:

var newShoppingcart = new ShoppingCart();
newShoppingcart.products.Add(product);
newShoppingcart.userID = userId;
db.Shoppingcarts.Add(newShoppingcart);
db.SaveChanges();

Just like you did above in your code.

Comments

0

You are adding the same record every time. Your statement (observation)

It adds an item to the cart but whenever i add another item the previous one is gone

is not completely true, because your saving the same product again and again. Check your code, you find the product as

Product product = db.Products.Find(ID);

and finally at bottom, you save that same product again

    ......
    ......
    shoppingcart.products.Add(product);
    shoppingcart.userID = userId;
    db.SaveChanges();
    return View("Index", shoppingcart);
}

You are doing no change. If an object has same 'Id' then it will overwrite the existing with same 'Id'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.