11

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?

2
  • 1
    use context.ChangeTracker.Entries().Where(x=> x.State == ... ) Commented Sep 15, 2015 at 19:41
  • 1
    @dotctor add as an answer so I can accept that answer Commented Sep 15, 2015 at 19:46

2 Answers 2

23

You can use DbContext.ChangeTracker

var modifiedEntries = context.ChangeTracker
       .Entries()
       .Where(x => x.State == EntityState.Modified)
       .Select(x =>x.Entity)
       .ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

How would I get the Modified Properties from ChangeTracker
@kevinc context.Entry(someObject).Properties.Where(m => m.IsModified);
@ScottE I don't see any Properties property available for DbEntityEntry class link
1

@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:

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


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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.