Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 552
alpav Avatar asked Mar 13 '13 20:03

alpav


2 Answers

It looks like things are different now (EF6). I was researching this to see if I needed to use an if statement when setting property values to see if the "new value" is different. I tested with the following and the entity is not marked as modified:

var things = dbContext.Things.AsQueryable();
var thing = things.First();
string name = thing.Name;
thing.Name = name;
var entry = dbContext.Entry(thing);
var state = entry.State;
int count = dbContext.ChangeTracker.Entries().Count(e => e.State == EntityState.Modified);
var modified = entry.Property(x => x.Name).IsModified;
like image 137
KevinVictor Avatar answered Oct 14 '22 22:10

KevinVictor


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

like image 43
Nikos Avatar answered Oct 14 '22 23:10

Nikos