【问题标题】:How can I delete items from my asp.net database如何从我的 asp.net 数据库中删除项目
【发布时间】:2016-04-22 01:39:20
【问题描述】:

我正在试用 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");
        }

【问题讨论】:

  • 了解数据库类型会有所帮助:mysql、sqlserver、dbase?
  • @Aaron 我安装了 SQL Server Express
  • ASP.NETweb 框架 - SQL Server (Express) 是数据库 ....

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


【解决方案1】:
    [HttpPost]
    public ActionResult Delete(Movie movie)
    {
        var dbMovie = db.Movies.find(movie.id);
        db.Movies.Remove(dbMovie);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

【讨论】:

  • 这会导致db.Movies.Remove(dbMovie) 处出现 NullPointerException。据我所知,Remove() 函数需要一个 Movie 实体。
  • dbMovie 应该是电影类型。也许 movie.id 为空?
  • 嗯..是的。我自己从来没有宣布过这个价值。但是为什么我需要使用movie.id 来标识要删除的电影,当Delete 方法传递要删除的电影作为参数时呢?我不明白你的代码。
  • 您需要某种方法来唯一标识要删除的电影。我建议使用 id 但你也可以做类似 db.movi​​es.where(x=> x.title == "Lion King").single()
  • 作为参数传递的电影未存储在数据库中,因此没有可删除的内容。您需要首先根据匹配的属性从数据库中获取电影,然后将其删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-27
  • 2012-01-27
  • 2017-12-11
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多