Linq对实体的更新问题

本文关键字:更新 新问题 实体 Linq | 更新日期: 2023-09-27 18:07:18

嗨,我有一个名为products…与列

             product_id  (p.K)
             product_name
             product_description
             product_price
             category_id  (F.k)

我有另一个表类别

                   category_id  (p.k)
                   category_name

我所尝试的是我试图更新产品表与category_id得到的问题我有以下代码....

         Private void btnsave_click(object sender , eventargs e)
         {
                 if (datagridview1.SelectedRows.Count > 0)
                 {
                     int updateproductid = Convert.ToInt32(datagridview1.SelectedRows[0].Cells[0].Value);
                     string productcategories =cbCategorytypes.Text;
                     var categorytypes = (from producttype in dbcontext.categories
                                          where producttype.name.Equals(productcategories)
                                          select producttype.categoryId).SingleOrDefault();
                     product product1 = new product() { productId = updateproductid };
                     dbcontext.products.Attach(product1);
                     product1.Name = txtProductname.Text;
                     product1.Description = txtProductdescription.Text;
                     product1.Price = Convert.ToDecimal(txtProductPrice.Text);
                     product1.categoryId = categorytypes;
                     dbcontext.SaveChanges();
                 }
         }

得到一个错误:Invalid Operation Exception Was Unhandled:具有相同key的对象已经在ObjectStateManager中存在。ObjectStateManager不能跟踪具有相同key的多个对象。

有谁能帮帮我.....

多谢…

Linq对实体的更新问题

您正在获得错误,因为您正在尝试更新的产品已被实体框架加载。您正在创建一个新的product实例,并分配一个现有的product id

您可以使用dbcontext.products DbSet的Local属性来检索现有产品。

 int updateproductid = Convert.ToInt32(datagridview1.SelectedRows[0].Cells[0].Value);
 string productcategories =cbCategorytypes.Text;
 var categorytypes = (from producttype in dbcontext.categories
                      where producttype.name.Equals(productcategories)
                      select producttype.categoryId).SingleOrDefault();
 product product1 = dbcontext.products.Local.Where(p => p.productId == updateproductid).First();
 product1.Name = txtProductname.Text;
 product1.Description = txtProductdescription.Text;
 product1.Price = Convert.ToDecimal(txtProductPrice.Text);
 product1.categoryId = categorytypes;
 dbcontext.SaveChanges();

你应该考虑使用合适的命名约定

这几行

product product1 = new product() { productId = updateproductid };
dbcontext.products.Attach(product1);

告诉我您正在创建一个新产品并将其附加到上下文。但是这个产品已经存在了。您应该根据updateproductid检索产品,并设置新的categoryId或您想要更改的属性。

更确切地说,你应该替换

product product1 = new product() { productId = updateproductid };
dbcontext.products.Attach(product1);

有这样的内容

product product1 = (from product in dbcontext.products 
                    where productId == updateproductid select product);