trying to update the category table with entities
I have a data gridview and i have two text boxes when i click on the data gridview row the corresponding row values are filled in text boxes ......
upto this working fine....
i want to update the category table when i click on the save button
i have category table with
category_id
category_name
category_description
and this is my code :
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 };
categoryu开发者_JS百科pdate.category_Name = tbCategoryName.Text;
categoryupdate.category_Description = tbCategoryDescription.Text;
dbcontext.SaveChanges();
}
}
it does not update the category table.....
would any one help on this.....
Your dbcontext
has no way of knowing that you are updating anything. Since you mentioned "updating" the table, here is one way of updating your categories table.
Updating:
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();
Now, if you want to insert on your categories table...
Inserting:
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
Your dbcontext
has no way to know that you created a category
object unless you tell it.
category categoryupdate = new category() { category_Id = updatecategoryid };
dbcontext.Attach(categoryupdate);
categoryupdate.category_Name = tbCategoryName.Text;
categoryupdate.category_Description = tbCategoryDescription.Text;
dbcontext.SaveChanges();
精彩评论