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')
);
Step back and think. Do you really want to download the records from the database in order to delete them? Just because you can doesn't make it a good idea.
Perhaps you could consider deleting the items from the database with a stored procedure? EF also allows to do that...
I'm dealing with this myself, and agree with Adi - just use sql.
I'm cleaning up old rows in a log table, and EF RemoveRange took 3 minutes to do the same thing this did in 3 seconds:
Date is the name of the column containing the date. To make it correct, use a parameter, of course, like this:
Note that there are a lot of rows involved in my case. When I started the project and didn't have a lot of data, RemoveRange worked fine.
Use an Variable to Store Removable list and pass it to RemoveRange().
I Usually do like this, and That's Work. Hope This also work in your case.
I think we reached here a limitation of EF. Sometimes you just have to use ExecuteSqlCommand to stay performant.
Why don't you just have an adapter to the database and just send the appropriate delete command like in your example?
It's a bit broken, try