Entity Framework AutoDetectChangesEnabled = false and .Find

时间:2015-07-08 15:38:20

标签: 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 ?

1 个答案:

答案 0 :(得分:4)

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:

dbContext.Users.AsNoTracking().ToList();