I am trying to delete multiple rows from a table.
In regular SQL Server, this would be simple as this:
DELETE FROM Table WHERE Table.Column = 'SomeRandomValue' AND Table.Column2 = 'AnotherRandomValue'
In Entity Framework 6, they have introduced RemoveRange() method.
However, when I use it, rather than deleting rows using the where clauses that I provided, Entity Framework queries the database to get all rows that match the where clauses and delete them one by one using their primary keys.
Is this the current limitation of EntityFramework? Or am I using RemoveRange()
wrong?
Following is how I am using RemoveRange()
:
db.Tables.RemoveRange( db.Tables .Where(_ => _.Column == 'SomeRandomValue' && _.Column2 == 'AnotherRandomValue') );
RemoveRange. The RemoveRange method is used for deleting multiple objects from the database in one method call. The following code deletes a large number of records from the database using RemoveRange.
Table select o; foreach (var row in rows) { dataDb. Table. Remove(row); } dataDb. SaveChanges();
RemoveRange() method attaches a collection of entities with Deleted state, which in turn will execute the DELETE command for all entities on SaveChanges() . Adding or removing entities using the AddRange and RemoveRange methods improves the performance.
Cascade delete automatically deletes dependent records or sets null to ForeignKey columns when the parent record is deleted in the database. Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.
I think we reached here a limitation of EF. Sometimes you just have to use ExecuteSqlCommand to stay performant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With