Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to delete multiple rows with Linq to Entity?

Hi I'm looking for efficient way to delete multiple records at once. I'm deleting 400 records and it takes 8-15 seconds. Here is my code

using (var entities = new Entity())
   {                               
       foreach (Item item in entities.Items.Where(x => x.id == id))
              entities.DeleteObject(item);
       entities.SaveChanges();
   }
like image 928
Michael Born Avatar asked May 19 '11 14:05

Michael Born


2 Answers

You can do it faster using EntityFramework.Extensions
1) First install EntityFramework.Extensions using NuGet

2) Here is the code similar to Linq2Sql's DeleteAllOnSubmit():

using EntityFramework.Extensions;

....

using (var entities = new Entity())
{                               
    entities.Items.Delete(x => x.id == id);
    entities.SaveChanges();
}

...
like image 175
Rajesh Avatar answered Sep 20 '22 16:09

Rajesh


Check out Bulk-deleting in LINQ to Entities or PLINQO for Entity Framework if it's the sort of delete you could do in a single batch, i.e.

DELETE FROM Entities WHERE [some condition]

Otherwise, maybe check you've got an index on the x column you're using to find each record.

like image 27
Chris Fulstow Avatar answered Sep 18 '22 16:09

Chris Fulstow