Entity Framework increasing performance with AutoDetectChangesEnabled

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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

1 thought on “Entity Framework increasing performance with AutoDetectChangesEnabled

  1. Thanks for a marvelous posting! I really enjoyed
    reading it, you happen to be a great author. I will be
    sure to bookmark your blog and will come back later in life.
    I want to encourage one to continue your great work,
    have a nice afternoon!

    my homepage blogs online

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.