如何使用Entity Framework按ID删除对象

149

在我的看法中,使用entity framework删除一个对象之前需要先获取它,代码如下:

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

context.DeleteObject(customer);

context.Savechanges();

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

13个回答

2
一个较小的版本(与以前的版本相比):
var customer = context.Find(id);
context.Delete(customer);
context.SaveChanges();

2
请为这段代码片段提供一些背景,并解释它比过去十年留下的其他答案做得更好的地方。 - miken32
1
不,问题的关键在于如何防止这种往返。 - Gert Arnold

1

原始的 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.
   }
}

24
这会使在Entity Framework中使用强类型对象功能失去意义。 - LawMan
4
这会损害 EF Identity 现金。但是,即使这样,EF 仍然会将您删除的实体返回给您。 - epox
1
它可以与Azure SQL DataWarehouse一起使用,而其他解决方案则不能。 - Michael Freidgeim
1
如果你这样做,那么最好不要使用ORM。我想这会影响EF缓存的性能。 - Storm Muller
1
这种风格容易受到SQL注入攻击的威胁。在这个特定的例子中,你是受保护的,因为变量是一个整数,但永远不要在字符串变量中使用这种模式。 - thelem
显示剩余2条评论

0

更简单易懂的版本。

var customer = context.Find<Customer>(id);
context.Remove(customer);
context.SaveChanges();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接