实体框架4.1:如何按对象ID删除 [英] Entity Framework 4.1: How do I delete by object Id

查看:196
本文介绍了实体框架4.1:如何按对象ID删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何删除从实体框架4.1的对象,而不必首先从数据库中加载的对象。我发现<一href="http://stackoverflow.com/questions/2471433/how-to-delete-an-object-by-id-with-entity-framework">these <一href="http://stackoverflow.com/questions/502795/how-do-i-delete-an-object-from-an-entity-framework-model-without-first-loading-it">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删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆