0

in my DbContext implementation if have a method called "IsModified". This is used by the application to show some kind of "Dirty" state. Within the method i access the ChangeTracker of the DbContext like shown below.

If i access the ChangeTracker.Entries while data is loaded / materialized from the database i get an InvalidOperationException because the internal stateentry collection has changed.

Is there a way to get around this without just using a try / catch. Or is there maybe a more efficient way of tracking the modified state of the context?

public bool IsModified()
{
    return this.ChangeTracker.Entries().Any(e => e.State != EntityState.Unchanged);
}
raisr
  • 13
  • 2

1 Answers1

0

Convert your DbContext to ObjectContext and try following implementation of IsModified:

var context = new YourDbContext();
var adapter = (IObjectContextAdapter)context;
var objectContext = adapter.ObjectContext;
...

public bool IsModified()
{
    bool modified = 
    context.ObjectStateManager.GetObjectStateEntries(~EntityState.Unchanged);
                               .Any();
    return modified;
}

you can also try to handle context.ObjectStateManager.ObjectStateManagerChanged event and update your property in this event. Should be more elegant.

Andrew
  • 3,648
  • 1
  • 15
  • 29
  • The solution with the ObjectStateManager.GetObjectStateEntries seems to work. Thanks. The ObjectStateManagerChanged event does not work because it only fires if items are added or deleted. Not when items are changed. http://msdn.microsoft.com/en-us/library/system.data.objects.objectstatemanager_events(v=vs.110).aspx – raisr Apr 15 '14 at 10:59
  • `~EntityState.Unchanged` means every state except for Unchanged. Every state including `EntityState.Detached`. Please test this case, to avoid bugs. – Andrew Apr 15 '14 at 11:46