2011-08-26 83 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版本... –