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

Viewed 24620

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?

5 Answers

Take a look at

myObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added)

here.

When I attempted to view the ObjectStateManager mentioned in the other answers it didn't show up in my debugger. When debugging in Visual Studio 2017, I've found it helpful to add the following snippet to a watch (which casts the dbContext object before referencing the ObjectStateManager property).

((System.Data.Entity.Infrastructure.IObjectContextAdapter)this.db).ObjectContext.ObjectStateManager

Once the watch is made, you can debug line by line watching what actions add to the various properties that list pending changes.

Related