Why there is no change in the database when you call context.SaveChanges ()?

public ViewResult Edit(int productId) { // тут делается выборка из БД Product product = repository.Products .FirstOrDefault(p => p.ProductID == productId); product.ProductID = product.ProductID; return View(product); // передается в представление в котором он // будет изменен, и будет вызвано действие по submit (HttpPost) } [HttpPost] public ActionResult Edit(Product product) { if(ModelState.IsValid) { repository.SaveProduct(product); // update return RedirectToAction("Index"); } else { return View(product); } } ... EFDbContext context = new EFDbContext(); public IQueryable<Product> Products { get{ return context.Products;} } public void SaveProduct(Product product) { if (product.ProductID == 0) { context.Products.Add(product); } **context.SaveChanges();** // почему то не происходит никаких изменений } ... 
  • 2 lines bother me: product.ProductID = product.ProductID; // what is it? ... if (product.ProductID == 0) {// possible if the condition is not saved - Specter
  • product.ProductID = product.ProductID; // what is it? oh, I accidentally inserted it, this code can be ignored as it does nothing (I experimented by changing the properties manually) if (product.ProductID == 0) - this is the condition for adding new products if ID = 0 in this case ID! = 0. When debugging context.SaveChanges () simply does not cause any SQL queries to change the database - Bogdan Sidor
  • that is, 2 queries to the database instead of one? and about "if (product.ProductID == 0)", you can make an extension for the context to check for a new entry or not, than duplicate the code, which is the result: if (context.ModelName.NewRecord) ... - pavelbel
  • one
    Although, even the condition to take out from the controller is necessary, so that the controller does not inflate, the model should be thick - pavelbel
  • Yes, the author of the code is not me at all, this is from the book "Pro ASP.NET MVC 3 Framework S. Sanderson, A. Freeman". I'm generally a beginner. - Bogdan Sidor

1 answer 1

The problem was solved by re-sampling the product from the database and changing all its properties in accordance with the product in the parameter. After that, SaveChanges () worked.