Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
926 views
Welcome To Ask or Share your Answers For Others

1 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 … … …
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...