2011-08-22 53 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

你會幫我在這... –