2011-08-26 49 views
0

我有一個數據GridView和我有兩個文本框,當我對數據的GridView單擊行相應的行值填充在文本框中類別表......試圖更新實體

高達這個工作的罰款....

我想更新類別表時,我的保存按鈕點擊

我有

       category_id 
           category_name 
           category_description 

,這我類別表或許這就是我的代碼:

    private void btnSave_Click(object sender, EventArgs e) 
       { 

         if(dgvCategories.SelectedRows.Count >0) 
         { 
        int updatecategoryid = Convert.ToInt32(dgvCategories.SelectedRows[0].Cells[0].Value); 
        category categoryupdate = new category() { category_Id = updatecategoryid }; 
        categoryupdate.category_Name = tbCategoryName.Text; 
        categoryupdate.category_Description = tbCategoryDescription.Text; 
        dbcontext.SaveChanges(); 
        } 

       } 

它不更新欄目表.....

將在此任意一個幫助.....

回答

1

您的dbcontext無法知道您正在更新什麼。由於您提到了「更新」表,因此以下是更新類別表的一種方法。

更新:

var category = dbcontext.Categories.Where(c => c.category_id.Equals(catId)).Single(); 
if (category != null) 
{ 
    category.category_name = tbCategoryName.Text; 
    category.category_description = tbCategoryDescription.Text; 
} 
dbcontext.SaveChanges(); 

現在,如果你想要插入您的類別表...

插入:

category c = new category(); 
c.category_name = tbCategoryName.Text; 
c.category_description = tbCategoryDescription.Text; 
dbcontext.Categories.AddObject(c); 
dbcontext.SaveChanges(); 
return c.category_id; //(optional) if you want the unique id to be returned 
0

dbcontext沒有辦法知道,除非您告訴它,否則您創建了一個category對象。

    category categoryupdate = new category() { category_Id = updatecategoryid }; 
       dbcontext.Attach(categoryupdate); 
       categoryupdate.category_Name = tbCategoryName.Text; 
       categoryupdate.category_Description = tbCategoryDescription.Text; 
       dbcontext.SaveChanges(); 
+0

錯誤:用空的EntityKey值的對象不能附加到對象上下文。 InvalidoperationException被取消打印。 –

+0

@ user852714:您使用的是什麼版本的實體框架? – StriplingWarrior

+0

E.F 1版本... –