Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I see the Entity Framework's pending changes?

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?

like image 294
Zack Peterson Avatar asked Feb 26 '09 21:02

Zack Peterson


People also ask

How does Entity Framework track changes?

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.

How does EF core detect changes?

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.

How do I turn off change tracking in Entity Framework?

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.

What is tracking in EF core?

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() .


2 Answers

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); 
like image 190
kjbartel Avatar answered Oct 10 '22 02:10

kjbartel


Take a look at

myObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added) 

here.

like image 40
Richard Avatar answered Oct 10 '22 03:10

Richard