2011-08-22 50 views
1

我只是得到了疯狂获得此更新与类别表和产品表相关的表...但我这样做不力成功...更新语句不工作的LINQ

我有这些表

   product product_id 
         product_name 
         product_description 
         product_price 
         product_image 


       category category_id 
         catgory_name 
         category_desc 

我有这样做了更新表....使用实体框架...

private void btnSave_Click(object sender, EventArgs e) 
    { 

     if (lblHiddenmode.Text == "Edit") 
     { 
      using (var dbcontext = new TsgEntities()) 
      { 
       pictureBox1.Enabled = true; 
       pictureBox1.Visible = true; 
       Image image = pictureBox1.Image; 
       byte[] bit = null; 

       bit = imageToByteArray(image); 
       product1 pd = new product1(); 

       string category = cbcategorytypes.Text; 
       string categorydesc = tbCategoryDescription.Text; 

       var c = new category { category_Name = category, category_Description = categorydesc }; 

       pd.product_Name = tbProductName.Text; 
       decimal price = Convert.ToDecimal(tbProductPrice.Text); 
       pd.product_Price = price; 
       pd.product_Description = tbProductdescription.Text; 
       pd.product_Image = bit; 
       pd.category = c;      
       dbcontext.SaveChanges();     
       this.Close(); 
      } 
     } 

    } 

注:我更新哪一个具有PRODUCT_ID的产品名称是4和category_id = 4

但它会在此声明中显示pd.category = c;我得到的product_id =“0”和CATEGORY_ID =“0”

我与类别表更新表时,我做错了..有与更新语句的任何问题

回答

2

你上面的代码将产生插入,而不是更新。为了执行更新,您首先需要从您的上下文中检索product1实例。

我不知道你的背景是什么样子,所以我不能发布确切的代码,但它会是这样的:

product1 pd = dbcontext.protucts.Where(p => p.productid == 4 
             && p.categoryid == 4).First(); 

然后,您可以进行更改,并呼吁dbcontext.SaveChanges()和它应该更新你的记录。

+0

我要怎么做,你会请亲密 –

+0

你会帮我在这个。 –

+0

非常感谢Adam对您的支持..... –

1

你实际上并没有增加你的对象进入你的背景。

你需要做的是这样的:

dbcontext.products.AddObject(pd1); 
+0

这是不工作..它不更新表.... –

+0

你会帮我在这... –