Search code examples
c#entity-frameworksql-delete

Delete a big list of items with Entity Framework


I want to delete a big list of items with EF, so I tried to remove them one by one but it take long time.

And I tried to use .RemoveAll() method with my list but it don't update the database [only remove from loaded entity]

So I use a SqlCommand to remove them from the database and I use .RemoveAll() to prevent EF unexpected number of rows update (0) exception.

Code:

dbContext.Database.ExecuteSqlCommand("DELETE FROM xxx WHERE xxx");
loadedEntity.subItems.ToList().RemoveAll(r => true);
dbContext.SaveChanges();

My question: is there a better way to do this?


Solution

  • try this

    var all = dbContext.XXX.Where(x => x.xxx == "xxx");
    dbContext.XXX.RemoveRange(all);
    dbContext.SaveChanges();