Skip to main content
 首页 » 编程设计

c#之linq to entities 的 linq 更新问题

2024年02月23日13xing901022

您好,我有一个名为 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(); 
                 } 
 
         } 

出现错误: 未处理无效操作异常:ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象。

有没有人能帮忙解决这个问题......

非常感谢....

请您参考如下方法:

您收到错误消息是因为您尝试更新的产品已由 Entity Framework 加载。您正在创建一个新的 product 实例并分配一个现有的 product id。

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

 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(); 

您应该考虑使用适当的命名约定