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 ?
Initially you find all entities whose state is not unchanged and save their entry. Then you set the state of every entity that isn't of your type TEntity and set their state to unchanged. Then call the base. SaveChanges() to save all changes to entities of your type.
By default, EF Core creates a snapshot of every entity's property values when it is first tracked by a DbContext instance. The values stored in this snapshot are then compared against the current values of the entity in order to determine which property values have changed.
AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.
In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With