Alternative to LINQ RemoveRange in EF 6

Viewed 40

I have two tables, Transactions and TransactionsStaging. I am using a LINQ query to fetch all rows in TransactionsStaging which have a duplicate in Trasactions and then removing them form TranscationsStaging. So ultimately I am removing all entries in TransactionsStaging which have a duplicate in Transactions table.

I have produced the following so far:

            IEnumerable<WebApi.Models.TransactionStaging> result = (from ts in db.TransactionsStaging
                            join t in db.Transactions
                            on ts.Description equals t.Description
                          select ts).ToList();
            db.TransactionsStaging.RemoveRange(result);
            db.SaveChanges();

The above works, but when inspecting the actual SQL queries being sent to the DB, I noticed that the RemoveRange produces a SQL DELETE statement for each row it is removing.

Is there a way to accomplish the same but avoid the multiple delete statements?

I wanted to explore this possibility before switching to executing a raw SQL statement rather than using Linq and ORM.

1 Answers

If you want to issue only a single database command, either a stored proc or raw SQL statements would be the way to go, since EntityFramework does not support bulk transactions.

You could go with a variety of bulk extensions available for batch operations.

Related