2010-03-18 148 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的核心工程驗證碼]