i use the EF5 and don’t know why a entity has the state “modified” after i set the only changed PropertyValue of this entity back to the original value.
using (TestDbContext context = new TestDbContext())
{
string name = context.Person.First().Name;
// count is 0
int count = context.ChangeTracker.Entries().Count(e => e.State == EntityState.Modified);
// Change Value
context.Person.First().Name = "Test";
// count is 1
count = context.ChangeTracker.Entries().Count(e => e.State == EntityState.Modified);
// Revert Value
context.Person.First().Name = name;
context.ChangeTracker.DetectChanges();
// count is 1
count = context.ChangeTracker.Entries().Count(e => e.State == EntityState.Modified);
}
Why? 🙁
Because Entity Framework only keeps track if the data got modified, not if it’s different from it’s original content.
We use a nifty method to reset the state to unmodified when the entity is unchanged:
Please note that this method is for EF 4.0, not for the newer versions with DbContext. But it is no problem to rewrite it to use EF 4.1+, I have done this myself already but I can’t find the code right now.