Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk-deleting in LINQ to Entities

Is there any way to bulk-delete a bunch of objects matching a given query in LINQ or LINQ-to-Entities? The only references that I can find are outdated, and it seems silly to iterate over and manually delete all objects I wish to remove.

like image 826
Benjamin Pollack Avatar asked May 15 '09 15:05

Benjamin Pollack


People also ask

How do I delete multiple records in Linq?

You can drag the SPROC to your DBML file and it will generate a rich method in your databasecontext class. Show activity on this post. First, you can find a list of the items you want to delete.

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 a record in LINQ query?

You can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands. LINQ to SQL does not support or recognize cascade-delete operations.

How do I delete a record in Entity Framework?

Delete a Record In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.


1 Answers

A while back I wrote a 4 part blog series (Parts 1, 2, 3 and 4) covering doing bulk updates (with one command) in the Entity Framework.

While the focus of that series was update, you could definitely use the principles involved to do delete.

So you should be able to write something like this:

var query = from c in ctx.Customers             where c.SalesPerson.Email == "..."             select c;  query.Delete(); 

All you need to do is implement the Delete() extension method. See the post series for hints on how...

Hope this helps

like image 79
Alex James Avatar answered Oct 08 '22 18:10

Alex James