C# 如何从asp.net数据库中删除项目
我正在试用asp.net,却被一个C# 如何从asp.net数据库中删除项目,c#,asp.net,asp.net-mvc,sql-server-express,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 (mo
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");
}
这是我的delete方法的代码,它不存在
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我安装了SQLServerExpresseDup。ASP.NET是web框架,SQL Server(Express)是数据库……这会导致在
db.Movies.Remove(dbMovie)
处出现NullPointerException。据我所知,Remove()
函数需要一个Movie
entity.dbMovie应该是Movie类型。也许movie.id是空的?嗯。。是 啊我自己从来没有申报过这个价值。但是,当delete方法将要删除的电影作为参数传递时,为什么我需要使用movie.id
来标识要删除的电影呢?我不明白你的代码。你需要某种方法来唯一标识要删除的电影。我建议使用id,但也可以使用db.movies.where(x=>x.title==“Lion King”).single()作为参数传递的电影不存储在数据库中,因此没有任何可删除的内容。您需要首先根据匹配的属性从数据库中获取电影,然后删除它。
[HttpPost]
public ActionResult Delete(Movie movie)
{
var dbMovie = db.Movies.find(movie.id);
db.Movies.Remove(dbMovie);
db.SaveChanges();
return RedirectToAction("Index");
}