Get a list of modified objects in Entity Framework 7

I'm DbContext updating to Entity Framework 7, and I usually override SaveChanges inside DbContext to be able to get a list of all changed objects before changing it. Ultimately, I have a script that starts tracking the previous version in the database. In Entity Framework 6, I would get model changes as follows:

 var oc = ((IObjectContextAdapter)this).ObjectContext; var modifiedItems = oc.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Deleted); List<ObjectStateEntry> ModifiedObjlist = modifiedItems.ToList(); 

However, now that the ObjectContext is deleted in Entity Framework 7, I'm stuck, how would I get a list of changed objects inside Entity Framework 7?

+7
c # entity-framework dbcontext entity-framework-core
source share
2 answers

You can use DbContext.ChangeTracker

 var modifiedEntries = context.ChangeTracker .Entries() .Where(x => x.State == EntityState.Modified) .Select(x =>x.Entity) .ToList(); 
+5
source share

@Dotctor code may not work in some cases.

There are certain cases where the change tracker may not have the latest information about objects controlled by the context, so the entity can be changed / added / deleted without notification of changes. To avoid this case, I would wrap the @dotctor code with the following condition:

 if(context.ChangeTracker.HasChanges()) { ... } 


Summary of Microsoft ChangeTracker.HasChanges () :

Checks if any new, deleted, or changed objects are tracked so that these changes are sent to the database if DbContext.SaveChanges or DbContext.SaveChangesAsync is called. Note that this method calls ChangeTracker.DetectChanges if ChangeTracker.AutoDetectChangesEnabled is set to false.

0
source share

All Articles