public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
//Oops~~~
context.SaveChanges();
}
[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
repository.SaveProduct(product);
//I can see this msg int the view page. but database never changed.!!
TempData["message"] = string.Format("{0} has been saved", product.Name);
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(product);
}
}
I got stuck with this problem and don’t know how to make the data be stored into the database. The problem occurs when I try to save changes to an existing product.
Can anyone tell me why the saveChanges() method called and datas never saved to the db? THX
The entity
productconstructed by model binding is NOT automatically attached to the context. The context therefore is not aware of any change to save. You have to attach the product first and set it’s state to modified.Now you can call
context.SaveChanges();.