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;