How to delete an object by id with entity framework

后端 未结 9 1887
你的背包
你的背包 2020-11-29 04:05

It seems to me that I have to retrieve an object before I delete it with entity framework like below

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


        
9条回答
  •  鱼传尺愫
    2020-11-29 04:58

    Raw sql query is fastest way I suppose

    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.
       }
    }
    

提交回复
热议问题