Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...