10

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();
   }
1

3 Answers 3

3

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();
}

...
Sign up to request clarification or add additional context in comments.

1 Comment

It requires package EntityFramework.Extended github.com/loresoft/EntityFramework.Extended
1

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.

1 Comment

query.Delete(); What logic Do I need to implement in Delete method? foreach loop and do the same ? How it will different?
0

In your loop:

using (var entities = new Entity()) 
{                                
    foreach (Item item in entities.Items.Where(x => x.id == id)) 
           entities.DeleteObject(item); 
    entities.SaveChanges(); 
} 

If you move the entities.SaveChanges(); so that it runs after the loop, it will run substantially faster.

using (var entities = new Entity()) 
{                                
    foreach (Item item in entities.Items.Where(x => x.id == id)) 
          entities.DeleteObject(item); 
} 
entities.SaveChanges(); 

2 Comments

-1: This code stub makes no sense, since the call to SaveChanges is placed outside the using scope where the entities variable does not exist.
Actually, this makes perfect sense. Correct that he mis-typed on accident, but this is the most correct answer from what I can tell. Just have to edit it a little, which I'll do now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.