2016-04-22 42 views
1

如何刪除項目我想了asp.net和我被難倒System.Data.Entity.Infrastructure.DbUpdateConcurrencyException。我嘗試在'刪除'操作方法中保存對數據庫的更改時發生異常。從我的asp.net數據庫

這裏是我的編輯方法的代碼,這工作完全正常:

 public ActionResult Edit(int id) 
     { 
      Movie movie = db.Movies.Find(id); 
      if (movie == null) 
      { 
       return HttpNotFound(); 
      } 
      return View(movie); 
     } 

     [HttpPost] 
     public ActionResult Edit(Movie movie) 
     { 
       db.Entry(movie).State = System.Data.Entity.EntityState.Modified; 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
     } 

這裏是不爲我的刪除方法的代碼!

 public ActionResult Delete(int id) 
     { 
      Movie movie = db.Movies.Find(id); 
      if (movie == null) 
      { 
       return HttpNotFound(); 
      } 
      return View(movie); 
     } 

     [HttpPost] 
     public ActionResult Delete(Movie movie) 
     { 
      db.Movies.Attach(movie); 
      db.Movies.Remove(movie); 
      //db.Entry(movie).State = System.Data.Entity.EntityState.Deleted; 
      //both the outcommented line above and the current method of marking for deletion result in the same exception on the line below. 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
+0

這將有助於瞭解數據庫類型:MySQL,SQLSERVER,質數據庫? – Velocibadgery

+0

@Aaron我安裝了SQL Server Express的 – user2651804

+0

可能DUP。 https://stackoverflow.com/questions/28660708/intermittent-system-data-entity-infrastructure-dbupdateconcurrencyexception –

回答

1
[HttpPost] 
    public ActionResult Delete(Movie movie) 
    { 
     var dbMovie = db.Movies.find(movie.id); 
     db.Movies.Remove(dbMovie); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
+0

這導致在'db.Movies.Remove(dbMovie)'一個NullPointerException。據我所知,'Remove()'函數需要一個'Movie'實體。 – user2651804

+0

dbMovie應該是電影類型。也許movie.id爲空? – kravits88

+0

嗯..是的。我從不聲明自己的價值。但爲什麼我需要使用'movie.id'來標識要刪除的影片,當Delete方法傳遞要刪除的影片作爲參數?我不明白你的代碼。 – user2651804