How to solve DbUpdateConcurrencyException when updating a row?

asp.net c# entity-framework

Question

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");
    }
}
1
12
1/8/2019 3:43:19 PM

Popular Answer

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 … … …
}
11
3/16/2016 6:02:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow