Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk deleting rows with RemoveRange()

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') ); 
like image 735
Peter Han Avatar asked Mar 03 '14 20:03

Peter Han


People also ask

How do I delete multiple rows in Entity Framework?

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.

How do I delete all records in Entity Framework?

Table select o; foreach (var row in rows) { dataDb. Table. Remove(row); } dataDb. SaveChanges();

How do I use RemoveRange in Entity Framework?

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.

Will Cascade delete entity framework?

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.


1 Answers

I think we reached here a limitation of EF. Sometimes you just have to use ExecuteSqlCommand to stay performant.

like image 78
Adi Avatar answered Sep 24 '22 18:09

Adi