本文介绍了实体框架4.1:如何按对象ID删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何删除从实体框架4.1的对象,而不必首先从数据库中加载的对象。我发现these other 2回答对堆栈溢出,但他们不属于EF 4.1
I would like to know how to delete an object from Entity Framework 4.1 without first having to load the object from the database. I have found these other 2 answers on Stack Overflow, but they do not pertain to EF 4.1
我曾尝试以下code,但它不能正常工作
I have tried the following code but it does not work
public void DeleteCar(int carId)
{
var car = new Car() { Id = carId };
_dbContext.Cars.Attach(car);
_dbContext.Cars.Remove(car);
_dbContext.SaveChanges();
}
我想避免低于code。
I want to avoid the code below.
public void DeleteCar(int carId)
{
var car = context.Cars.Find(carId);
_dbContext.Cars.Remove(car);
_dbContext.SaveChanges();
}
和我不想要调用存储过程或执行原始的SQL。
And I do not want to call a stored procedure or execute raw sql.
推荐答案
我用下面我删除,工程巨大。
I use the following for my deletes, works great.
public virtual ActionResult Delete(int commentID)
{
var c = new Comment(){CommentID = commentID};
db.Entry(c).State= EntityState.Deleted;
db.SaveChanges();
return RedirectToAction(MVC.Blog.AdminComment.Index());
}
这篇关于实体框架4.1:如何按对象ID删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!