How do I delete multiple rows in Entity Framework Core?
c#, entity-framework-core
Solution
because I get an error "InvalidOperationException: Collection was modified; enumeration operation may not execute" after the first object. In other words, .Remove removes only one object.
This has nothing to do with EF Core, and, yes, `.Remove()` only removes one object. However, you are attempting to modify a collection that you are iterating through. There are ways to do this, but this isn't a good route to go.
Entity Framework Core does NOT have .RemoveRange, so I have no idea how to perform this operation.
There are definitely at least a couple simple ways to delete multiple records in EF Core. And, EF Core does have a `RemoveRange()` method - it's a method on `DbSet<TEntity>`, see here in the API docs (as stated in the comment above).
A couple options:
If `myCollection` is of a type that belongs to a `DbSet<TEntity>`, a simple call such as this will do the trick:
_dbContext.MyEntities.RemoveRange(myCollection);
_dbContext.SaveChanges();
If `myCollection` is actually a navigation property off of an entity that you queried, you can call `.Clear()` on the collection instead of iterating and calling `.Remove()`.
var myParentEntity = _dbContext.MyParentEntities
.Include(x => x.MyChildrenEntities)
.Single(x => x.Id == id);
myParentEntity.MyChildrenEntities.Clear();
_dbContext.SaveChanges();
As also commented above, there's a lot of context missing on your question - more complete code should be posted. I'm just taking a couple stabs in the dark to get you up and running with EF Core!
Problem
I need to delete multiple rows from a database using Entity Framework Core. This code does NOT work: ``` foreach (var item in items) { myCollection.Remove(item); } ``` because I get an error "InvalidOperationException: Collection was modified; enumeration operation may not execute" after the first object. In other words, .Remove removes only one object. Entity Framework Core does NOT have .RemoveRange, so I have no idea how to perform this operation. In order to preserve maximum compatibility with the various database providers, I would prefer NOT to call context.Database.ExecuteSqlCommand("delete from physical_table where..."). Is there a suitable solution? Thanks!