Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve DbUpdateConcurrencyException when updating a row?

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");
    }
}
like image 521
Amit Hasan Avatar asked Oct 01 '14 19:10

Amit Hasan


1 Answers

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 … … …
}
like image 199
Amit Hasan Avatar answered Sep 28 '22 04:09

Amit Hasan