在我看來,我要檢索對象之前,我與實體框架刪除它像下面如何通過ID與實體框架刪除對象
var customer = context.Customers.First(c => c.Id = 1);
context.DeleteObject(customer);
context.Savechanges();
所以我需要打兩次數據庫。有更簡單的方法嗎?
在我看來,我要檢索對象之前,我與實體框架刪除它像下面如何通過ID與實體框架刪除對象
var customer = context.Customers.First(c => c.Id = 1);
context.DeleteObject(customer);
context.Savechanges();
所以我需要打兩次數據庫。有更簡單的方法嗎?
如果您使用的是EF 1.0,那就是最簡潔的方法。可能有其他方式,但他們比他們值得恕我直言更麻煩。
如果你不想查詢它只是創建一個實體,然後刪除它。
Customer customer = new Customer() { Id = 1 } ;
context.AttachTo("Customers", customer);
context.DeleteObject(customer);
context.Savechanges();
同樣作爲@Nix用小的變化是強類型:
如果你不想查詢它只是創建一個實體,然後將其刪除。
Customer customer = new Customer() { Id = id };
context.Customers.Attach(customer);
context.Customers.DeleteObject(customer);
context.SaveChanges();
不完美,因爲如果缺少對象,它會引發異常:「DbUpdateConcurrencyException:存儲更新,插入或刪除語句會影響意外的行數(0)。」我希望它忽略這個,就像DELETE語句一樣。 – Dunc 2015-01-22 15:34:08
對不起,這導致驗證,這是不需要和預料永遠! – 2017-07-16 12:35:17
同類問題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();
它對批量刪除也很有用。
目前,這不屬於核心EF庫的一部分,這無法說明原因。 – nathanchere 2013-12-04 06:18:28
@FerretallicA - 同意。 – acarlon 2013-12-08 04:15:22
此方法已過時使用: context.Users.Where(user => user.Id == id).Delete(); – Manuel 2016-02-12 09:22:06
原始的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.
}
}
在實體框架6的刪除動作是Remove
。下面是一個例子
Customer customer = new Customer() { Id = id };
context.Customers.Attach(customer);
context.Customers.Remove(customer);
context.SaveChanges();
這對我有用 – 2017-08-25 17:26:01
我使用下面的代碼在我的項目之一:
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的核心工程驗證碼]
http://j.mp/f0x0Bh是你的答案。這是一個不錯的通用方法 – BritishDeveloper 2011-03-28 14:16:57