如何从我的asp.net数据库中删除项目

时间:2016-04-22 01:39:21

标签: c# asp.net asp.net-mvc sql-server-express

我正在试用asp.net而且我被System.Data.Entity.Infrastructure.DbUpdateConcurrencyException难倒了。我尝试在“删除”中删除对数据库的更改的行发生异常。行动方法。

这是我编辑方法的代码,完全正常:

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

1 个答案:

答案 0 :(得分:1)

    [HttpPost]
    public ActionResult Delete(Movie movie)
    {
        var dbMovie = db.Movies.find(movie.id);
        db.Movies.Remove(dbMovie);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
相关问题