1

I'm trying out asp.net and I'm stumped by a System.Data.Entity.Infrastructure.DbUpdateConcurrencyException. The exception occurs on the line I try to save changes to my database in the 'Delete' action method.

Here is my code for the edit method, which works perfectly fine:

 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"); } 

And here is the code for my delete method which does not!

 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"); } 
4
  • It would be helpful to know the database type: mysql, sqlserver, dbase? Commented Apr 22, 2016 at 2:09
  • @Aaron I installed SQL Server Express Commented Apr 22, 2016 at 2:35
  • Possible dup. stackoverflow.com/questions/28660708/… Commented Apr 22, 2016 at 2:38
  • ASP.NET is the web framework - SQL Server (Express) is the database .... Commented Apr 22, 2016 at 4:41

1 Answer 1

1
 [HttpPost] public ActionResult Delete(Movie movie) { var dbMovie = db.Movies.find(movie.id); db.Movies.Remove(dbMovie); db.SaveChanges(); return RedirectToAction("Index"); } 
Sign up to request clarification or add additional context in comments.

5 Comments

This results in a NullPointerException at db.Movies.Remove(dbMovie). As far as I can read, the Remove() function expects a Movie entity.
dbMovie should be Movie type. Maybe movie.id is null?
Hmm.. yeah. I never declare that value myself. But why do I need to use a movie.id to identify a movie to delete, when the Delete method is passed the movie to delete as an argument? I don't understand your code.
You need some way to uniquely identify which movie to delete. I would recommend using id but you could also do something like db.movies.where(x=> x.title == "Lion King").single()
The movie passed as an argument is not stored in the database so there is nothing to delete. You need to get the movie from the db first based on matching properties, then delete that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.