I'm using the entity framework code first approach for an ASP.NET MVC application. After editing a row when submitting for saving the change I'm getting the following error for the http post method:
An exception of type 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll but was not handled in user code.
This error is encountered at db.SaveChanges().
db.Entry<Project>(EditedProj).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
Main code:
[HttpGet]
public ActionResult Edit(int id)
{
using (var db = new ProjectContext())
{
return View(db.Projects.Find(id));
}
}
[HttpPost]
public ActionResult Edit(Project EditedProj)
{
using (var db = new ProjectContext())
{
db.Entry<Project>(EditedProj).State =
System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Projects");
}
}
I have found the answer. I was not passing id value for Http Post action method.
As stated in this link
Exception thrown by DbContext when it was expected that SaveChanges for an entity would result in a database update but in fact no rows in the database were affected.
In my case the above statement is true because I was trying to update a row but without id no row was updated. Hence, the exception.
It can be done using a hidden input element which contains the id. The code below shows how to do it in Edit.cshtml –
@using (Html.BeginForm("Edit", "Home", FormMethod.Post,
new { @class = "form-horizontal", role = "form" }))
{
@Html.HiddenFor(m => m.ProjectID)
//Other code … … …
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With