Bulk deleting rows with RemoveRange()

2019-02-05 19:05发布

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')
);

7条回答
等我变得足够好
2楼-- · 2019-02-05 19:07

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...

查看更多
Evening l夕情丶
3楼-- · 2019-02-05 19:13

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:

DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < -6

Date is the name of the column containing the date. To make it correct, use a parameter, of course, like this:

  context.Database.ExecuteSqlCommand
      ("DELETE FROM  LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < @DaysOld", new System.Data.SqlClient.SqlParameter(
                        "DaysOld", - Settings.DaysToKeepDBLogEntries));

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.

查看更多
爷、活的狠高调
4楼-- · 2019-02-05 19:16
var db1 =  db.Tables
        .Where(_ => _.Column == 'SomeRandomValue'
            && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList();
db.Tables.RemoveRange(db1);
db.SaveChanges();

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.

查看更多
成全新的幸福
5楼-- · 2019-02-05 19:21

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

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-02-05 19:23

Why don't you just have an adapter to the database and just send the appropriate delete command like in your example?

查看更多
相关推荐>>
7楼-- · 2019-02-05 19:26

It's a bit broken, try

db.Tables.RemoveRange(
    db.Tables
        .Where(_ => _.Column == 'SomeRandomValue'
            && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList()
);
db.SaveChanges();
查看更多
登录 后发表回答