Entity Framework AutoDetectChangesEnabled = false and .Find

c# entity-framework


Recently I've found about option AutoDetectChangesEnabled in EF, and in official documentation it is stated that manually handling AutoDetectChangesEnabled could cause "subtle bugs".

As I understand things could go wrong when saving changed entities to database, so my question is: is this piece of code safe (By default, the Entity Framework performs Detect Changes automatically when Find is called):

using (var context = new DbContext())
    context.Configuration.AutoDetectChangesEnabled = false;
    var user = context.users.Find(id);
    context.Configuration.AutoDetectChangesEnabled = true;

    return user;

So, as you can see, I'm not making any changes to my entities, just returning them, and if AutoDetectChangesEnabled is set to false will Find still hit Cache firstly and then database ?

7/8/2015 3:38:19 PM

Accepted Answer

Disabling AutoDetectChangesEnabled is not a problem, you are just disabling a feature. Entity Framework will not track changes in your entities and you'll have to flag them manually before SaveChanges.

Activating it and deactivating it the way you did makes no sense because your are creating a context in a using block. That means that after you use it, you are disposing it. So, you don't need to activate it again.

On the other hand, instead of deactivating change detection, you can use AsNoTracking() when you get objects from the database. That will speed up your queries but you still have the change detection feature available for other entities. It's something like this:

5/9/2016 9:52:35 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow