Question

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);
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top