Search code examples
entity-frameworkentity-framework-4updates

Does entity framework compare assigned values with original to determine IsModified flag?


If I load entity object and then assign one of properties to the same value as it had before, does framework detect changes or it would set IsModified flag to true anyway ?

This is how generated code for field Name looks like:

OnNameChanging(value);
ReportPropertyChanging("Name");
_Name = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Name");
OnNameChanged();

I don't know which of those events set IsModified flag for that field and for the whole entity.


Solution

  • Your context only keeps track if your data got modified, not if it's different.

    You can do a check like this:

      private void CheckIfDifferent(DbEntityEntry entry)
        {
            if (entry.State != EntityState.Modified) 
                return;
    
            if (entry.OriginalValues.PropertyNames.Any(propertyName => !entry.OriginalValues[propertyName].Equals(entry.CurrentValues[propertyName])))
                return;
    
           (this.dbContext as IObjectContextAdapter).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity).ChangeState(EntityState.Unchanged);
        }
    

    source:https://stackoverflow.com/a/13515869/1339087