Entity Framework 4.1: How do I delete by object Id

Paul picture Paul · Aug 4, 2011 · Viewed 26.2k times · Source

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

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

I want to avoid the code below.

public void DeleteCar(int carId)
{
  var car = context.Cars.Find(carId);
  _dbContext.Cars.Remove(car);
  _dbContext.SaveChanges();
}

And I do not want to call a stored procedure or execute raw sql.

Answer

agradl picture agradl · Aug 15, 2011

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

enter image description here