user147372
user147372

Reputation: 39

Deleting a collection in an entity

I have a entity that has a collection of entities and I wish to delete that collection. The collection is 15K or so and it takes a long time to do a normal delete.

Page objPage = context.Pages.Where(p => p.PageID == "27486451851").First();
objPage.UserPosts.ForEach(x => { context.Posts.Remove(x); });

How can I get better performance on this?

Upvotes: 0

Views: 102

Answers (3)

Ray Saltrelli
Ray Saltrelli

Reputation: 4218

I've observed significant performance degradation while adding and removing a large number of entities with DbContext.Configuration.AutoDetectChangesEnabled = true. For some strange reason, EF calls DbContext.ChangeTracker.DetectChanges() under the hood each time you call DbSet<T>.Add() or DbSet<T>.Remove(). This causes the ChangeTracker to iterate through every entity in the entire collection looking for changes with each addition/removal. This seems completely unnecessary.

A possible solution is the following, which puts off change detection until you have removed all of your Post entities, thereby calling context.ChangeTracker.DetectChanges() only once.

context.Configuration.AutoDetectChangesEnabled = false;
Page objPage = context.Pages.Where(p => p.PageID == "27486451851").First();
objPage.UserPosts.ForEach(x => { context.Posts.Remove(x); });
context.ChangeTracker.DetectChanges();
context.SaveChanges();
context.Configuration.AutoDetectChangesEnabled = true;

Upvotes: 1

Martin Mulder
Martin Mulder

Reputation: 12934

Use:

context.ExecuteStoreCommand("DELETE FROM [UsersPosts] WHERE PageID = @0", 27486451851);

Upvotes: 1

AaronLS
AaronLS

Reputation: 38392

using (var context = new DatabaseEntities())
{
    context.ExecuteStoreCommand("DELETE FROM Pages WHERE PageID == {0}", "27486451851");
}

Upvotes: -1

Related Questions