Entity Framework increasing performance with AutoDetectChangesEnabled
Posted on: 2012-09-05
If you need to insert a lot of data into the framework with Microsoft Entity Framework you may want to set the AutoDetectChangesEnabled
to false. This will improve performance because the DetectChanges won't execute the detection of changes in the objec.
public virtual void DetectChanges(bool force = false) {
if (this.AutoDetectChangesEnabled || force) {
this.ObjectContext.DetectChanges ();
}
}
To disable the auto detect changes you need to set the context to false. the AutoDetectChanges is inside the Configuration property.
context.Configuration.AutoDetectChangesEnabled = false;
This method "DetectChanges" will be called when you use the Add, Attach, Find, Local, or Remove members on DbSet. Also, it will be called if you use GetValidationErrors, Entry, or SaveChanges members on DbContext. This is the reason that batch Adding object with Entity Framework can be slow because the detection.
DetectChanges do a copy of every entity added to the context and will verify if a change has been made when everything is commited to the database (Saved). Every time that DetectChange is called it has to go through all of your tracked entities each time its called, so the more stuff you have in your context the longer it takes to traverse.
So, it's possible to disable the detect change and call it manually if you need to increase speed. But, in most case you can stay the detection automatically without a big loss of performance.
YourDbContext.ChangeTracker.DetectChanges(); //Manually detect changes
From my experience, the performance isn't affected if you play with less than 100 objects. It's easier to let the framework handle changes in this case. But, if you need to add or modify over 100 objects, I recommend that you manually remove the automatic changes detection and to manually call the DetectChanges.