Get List of Modified Objects within Entity Framework 7

.net c# dbcontext entity-framework entity-framework-core


I am stumped - upgrading to Entity Framework 7 and I typically override the SaveChanges inside the DbContext to be able to get a list of all the Modified Objects before it changes. Ultimately I have a script that fires that tracks the previous version in a database. In Entity Framework 6 I would get the model changes like so:

var oc = ((IObjectContextAdapter)this).ObjectContext;
var modifiedItems = oc.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Deleted);

List<ObjectStateEntry> ModifiedObjlist = modifiedItems.ToList();

However now that ObjectContext is removed within Entity Framework 7, I am stuck, how would I inside Entity Framework 7 get a list of the modified objects?

1/6/2016 11:57:08 AM

Accepted Answer

You can use DbContext.ChangeTracker

var modifiedEntries = context.ChangeTracker
       .Where(x => x.State == EntityState.Modified)
       .Select(x =>x.Entity)
9/15/2015 7:53:33 PM

Popular Answer

@dotctor 's code may not work in some cases.

There are certain instances where the change tracker may not have the latest information with regards to the entities being managed by the context, so an entity could be modified/added/deleted without the change tracker being aware. To avoid this case, I would wrap the @dotctor 's code in the following conditional:


Microsoft Summary of ChangeTracker.HasChanges():

Checks if any new, deleted, or changed entities are being tracked such that these changes will be sent to the database if DbContext.SaveChanges or DbContext.SaveChangesAsync is called. Note that this method calls ChangeTracker.DetectChanges unless ChangeTracker.AutoDetectChangesEnabled has been set to false.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow