简体   繁体   English

实体框架4.1:如何按对象ID删除

[英]Entity Framework 4.1: How do I delete by object Id

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. 我想知道如何在不首先从数据库加载对象的情况下从Entity Framework 4.1中删除对象。 I have found these other 2 answers on Stack Overflow, but they do not pertain to EF 4.1 我发现这些 其他的堆栈溢出2个回答,但他们不属于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. 我不想调用存储过程或执行原始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());
}

在此输入图像描述

Just to convince you that your first code snippet must work here is a simple example you can copy, paste and test: 只是为了说服你,你的第一个代码片段必须在这里工作,这是一个简单的例子,你可以复制,粘贴和测试:

  • Create a new console application project (.NET 4) 创建一个新的控制台应用程序项目(.NET 4)
  • Add reference to EntityFramework.dll (EF 4.1) 添加对EntityFramework.dll引用(EF 4.1)
  • Delete the content of Program.cs and paste in the following: 删除Program.cs的内容并粘贴如下:

-> - >

using System.Data.Entity;

namespace EFDeleteTest
{
    public class Car
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class MyContext : DbContext
    {
        public DbSet<Car> Cars { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Database with name "EFDeleteTest.MyContext"
            // will be created automatically in SQL Server Express

            int carId = 0;
            using (var context = new MyContext())
            {
                var car = new Car { Name = "Test" };
                context.Cars.Add(car);
                context.SaveChanges();

                carId = car.Id;
            }
            //Make breakpoint here and check that the car is indeed in the DB

            using (var context = new MyContext())
            {
                var car = new Car() { Id = carId };
                context.Cars.Attach(car);
                context.Cars.Remove(car);
                context.SaveChanges();
            }
            //Make breakpoint here and check that the car
            //indeed has been deleted from DB
        }
    }
}

If you have a SQL Server Express DB it will automatically create the DB. 如果您有SQL Server Express DB,它将自动创建数据库。

Perhaps this might help you to compare with your code because it looks as if something not visible in your code fragments is causing the different behaviour you describe. 也许这可能有助于您与代码进行比较,因为它看起来好像在您的代码片段中看不到的东西导致您描述的不同行为。

use stub entities: 使用存根实体:

public void DeleteCar(int carId)
{
  var car = new Car() { Id = carId };
  _dbContext.AttachTo("Cars",car); 
  _dbContext.DeleteObject(car); 
  _dbContext.SaveChanges();
}

reference: 参考:

http://blogs.msdn.com/b/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx http://blogs.msdn.com/b/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx

The following code works well for me: 以下代码适用于我:

var c = db.Set<T>().Find(id);
db.Entry(c).State = EntityState.Deleted;
db.SaveChanges();

If this object wasn't tracked previously by the DbContext then it would hit the database, otherwise it would find it in memory. 如果DbContext以前没有跟踪过这个对象,那么它会命中数据库,否则会在内存中找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM