在我的看法中,使用entity framework删除一个对象之前需要先获取它,代码如下:
var customer = context.Customers.First(c => c.Id == 1);
context.DeleteObject(customer);
context.Savechanges();
所以我需要两次访问数据库。有更简单的方法吗?
在我的看法中,使用entity framework删除一个对象之前需要先获取它,代码如下:
var customer = context.Customers.First(c => c.Id == 1);
context.DeleteObject(customer);
context.Savechanges();
所以我需要两次访问数据库。有更简单的方法吗?
var customer = context.Find(id);
context.Delete(customer);
context.SaveChanges();
原始的 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.
}
}
更简单易懂的版本。
var customer = context.Find<Customer>(id);
context.Remove(customer);
context.SaveChanges();