2010-03-18 149 views
64

在我看来,我要检索对象之前,我与实体框架删除它像下面如何通过ID与实体框架删除对象

var customer = context.Customers.First(c => c.Id = 1); 

context.DeleteObject(customer); 

context.Savechanges(); 

所以我需要打两次数据库。有更简单的方法吗?

+0

http://j.mp/f0x0Bh是你的答案。这是一个不错的通用方法 – BritishDeveloper 2011-03-28 14:16:57

回答

0

如果您使用的是EF 1.0,那就是最简洁的方法。可能有其他方式,但他们比他们值得恕我直言更麻烦。

20

如果你不想查询它只是创建一个实体,然后删除它。

Customer customer = new Customer() { Id = 1 } ; 
context.AttachTo("Customers", customer); 
context.DeleteObject(customer); 
context.Savechanges(); 
44

同样作为@Nix用小的变化是强类型:

如果你不想查询它只是创建一个实体,然后将其删除。

   Customer customer = new Customer() { Id = id }; 
       context.Customers.Attach(customer); 
       context.Customers.DeleteObject(customer); 
       context.SaveChanges(); 
+4

不完美,因为如果缺少对象,它会引发异常:“DbUpdateConcurrencyException:存储更新,插入或删除语句会影响意外的行数(0)。”我希望它忽略这个,就像DELETE语句一样。 – Dunc 2015-01-22 15:34:08

+0

对不起,这导致验证,这是不需要和预料永远! – 2017-07-16 12:35:17

20

同类问题here

使用实体框架有EntityFramework-Plus(扩展库)。
NuGet上可用。然后你可以写下类似的东西:

// DELETE all users which has been inactive for 2 years 
ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2)) 
    .Delete(); 

它对批量删除也很有用。

+18

目前,这不属于核心EF库的一部分,这无法说明原因。 – nathanchere 2013-12-04 06:18:28

+1

@FerretallicA - 同意。 – acarlon 2013-12-08 04:15:22

+1

此方法已过时使用: context.Users.Where(user => user.Id == id).Delete(); – Manuel 2016-02-12 09:22:06

4

原始的SQL查询是最快的方式,我想

public void DeleteCustomer(int id) 
{ 
    using (var context = new Context()) 
    { 
     const string query = "DELETE FROM [dbo].[Customers] WHERE [id]={0}"; 
     var rows = context.Database.ExecuteSqlCommand(query,id); 
     // rows >= 1 - count of deleted rows, 
     // rows = 0 - nothing to delete. 
    } 
} 
+5

这打破了在EF中使用强类型对象功能的目的。 – LawMan 2015-03-04 17:20:23

+0

这会影响EF身份证现金。此后EF仍然会将您的已删除实体返回给您。 – epox 2016-08-26 23:17:48

+1

当其他解决方案不适用时,它可以与Azure SQL DataWarehouse一起使用。 – 2016-09-08 11:37:27

39

在实体框架6的删除动作是Remove。下面是一个例子

Customer customer = new Customer() { Id = id }; 
context.Customers.Attach(customer); 
context.Customers.Remove(customer); 
context.SaveChanges(); 
+0

这对我有用 – 2017-08-25 17:26:01

2

我使用下面的代码在我的项目之一:

using (var _context = new DBContext(new DbContextOptions<DBContext>())) 
    { 
     try 
     { 
      _context.MyItems.Remove(new MyItem() { MyItemId = id }); 
      await _context.SaveChangesAsync(); 
     } 
     catch (Exception ex) 
     { 
      if (!_context.MyItems.Any(i => i.MyItemId == id)) 
      { 
       return NotFound(); 
      } 
      else 
      { 
       throw ex; 
      } 
     } 
    } 

这样一来,只有在尝试删除的项目时发生异常,将查询数据库两次与指定的ID。然后,如果找不到该项目,它将返回一条有意义的消息;否则,它只是抛出异常(你可以使用不同的异常类型使用不同的catch块来更适合你的情况,使用if块等添加更多的自定义检查)。

[我正在使用实体框架核心MVC的.Net核心/ .NET的核心工程验证码]