简体   繁体   English

努力使用实体框架将数据保存到ASP.NET MVC中的数据库

[英]Struggling with saving data to database in ASP.NET MVC with Entity Framework

I am just starting to learn C# & ASP.NET MVC framework and I am trying to build a shopping cart functionality. 我刚刚开始学习C#和ASP.NET MVC框架,并且正在尝试构建购物车功能。 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! 非常感谢您的帮助,请原谅我的noob代码!

When you fetching ShoppingCart from db it dosen't fetch products list. 当您从数据库获取ShoppingCart ,它不会获取产品列表。 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. 因此ShoppingCart.products始终为null,您可以创建new List<Product>()并向其中添加一种产品。 Thats why you have only one product in ShoppingCart.products list. 这就是为什么ShoppingCart.products列表中只有一种产品。 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 . 您可以使用EF延迟加载 In your example you can add virtual keyword to products property to load it form db when needed: 在您的示例中,您可以将virtual关键字添加到products属性,以便在需要时从db加载它:

...
public virtual List<Product> products { get; set; }

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. 就像您在上面的代码中所做的一样。

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'. 如果对象具有相同的“ Id”,则它将使用相同的“ Id”覆盖现有对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 asp.net mvc 4 + Entity Framework 将图像保存到数据库 - Saving images to database with asp.net mvc 4 + Entity Framework ASP.Net脚手架MVC努力使用实体框架填充下拉列表 - ASP.Net Scaffolded MVC Struggling to populate a dropdownlist with Entity Framework PopUp 不在 ASP.NET MVC 5 和实体框架中的数据库中发送数据 - PopUp not sending data in database in ASP.NET MVC 5 and Entity Framework ASP.NET MVC不在数据库上保存数据 - ASP.NET MVC not saving data on database 在实体框架中编辑对象并将其保存到ASP.NET MVC 2.0中的数据库中 - Editing an object in entity framework and saving it to the database in ASP.NET MVC 2.0 带有ASP.NET MVC的实体框架将值保存到错误的列 - Entity Framework with ASP.NET MVC is saving value to wrong column ASP.net MVC与Entity Framework重新排序数据库记录 - ASP.net MVC with Entity Framework reordering database records ASP.NET MVC 4实体框架数据库第一个存储库 - ASP.NET MVC 4 Entity Framework Database First Repository 配方-Entity Framework ASP.NET MVC中的成分数据库 - Recipe - ingredients database in Entity Framework ASP.NET MVC Entity Framework Core 和 ASP.NET Core MVC 中的 Inheritance 数据库 - Inheritance Database in Entity Framework Core and ASP.NET Core MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM