I'm creating an application with the ADO.NET Entity Framework.
I can step through my code line-by-line while debugging and watch SQL Server Profiler for every query executed, but I can't figure out where all those SQL commands are coming from!
Sometimes when I execute SaveChanges()
, the Entity Framework performs unexpected, weird INSERTS. They sometimes break the application. I can't figure out what I'm doing to cause them.
How can I monitor the pending changes that queue up waiting for a SaveChanges()
call?
By default, Entity Framework tracks changes of the loaded entities during the life-time of the context. The Change Tracking tracks changes when you add new records, update or delete the existing records. These track changes are lost if they are not saved before the DbContext object is destroyed.
EF Core change tracking works best when the same DbContext instance is used to both query for entities and update them by calling SaveChanges. This is because EF Core automatically tracks the state of queried entities and then detects any changes made to these entities when SaveChanges is called.
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.
Tracking behavior controls if Entity Framework Core will keep information about an entity instance in its change tracker. If an entity is tracked, any changes detected in the entity will be persisted to the database during SaveChanges() .
Since Entity Framework 5.0 DbContext
has a ChangeTracker
property which has all pending changes. Similar to the ObjectStateManager
you can get entities in various states as follows:
myDbContext.ChangeTracker.Entries().Where(e => e.State == EntityState.Added); myDbContext.ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted); myDbContext.ChangeTracker.Entries().Where(e => e.State == EntityState.Modified);
Take a look at
myObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
here.
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