2
        //Person.Name is "Peter"
        Person person = DbContext.People.Where(x => x.Id == 0).FirstOrDefault();
        bool b = DbContext.ChangeTracker.HasChanges(); //return false;
        person.Name = "Patrick";
        b = DbContext.ChangeTracker.HasChanges(); //return true;
        person.Name = "Peter";
        b = DbContext.ChangeTracker.HasChanges(); //expect false but return true;

Based on the code above, am I right to say that once the entity has changed, dbcontext's changetracker doesn't bother to check if the value has been reverted?

Joe Taras
  • 15,166
  • 7
  • 42
  • 55
  • Hello and welcome to StackOverflow. It looks like you haven't taken the [tour], I recommend you do that and also read the help page section about [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and [edit] your question to include at least a [mcve], and preferably also input and expected output – MindSwipe May 18 '20 at 10:11
  • 1
    Most likely the classes you use doesn't actually track their current value compared to the original value, they only have 1 set of values, the current one, and changing that makes the object count as updated, even if you "update" it back. However, you will have to share some code in order to anyone to be able to help you. Additionally, please write an actual question. From the documentation I would say your observation is correct, changing an object flags it as updated, it says nothing about changing it back reverts that tracking. – Lasse V. Karlsen May 18 '20 at 10:12
  • @LasseV.Karlsen hi i have updated the question. Sorry it's my first time posting here. – Hai Long Ng May 18 '20 at 10:24

1 Answers1

1

When you change a property value, the EF DbContext state set to Modified, so if you want to return on state of Unchanged you must explicity set this:

DbContext.Entry(yourEntry).State = EntityState.Unchanged;

An useful question/answer is here

Joe Taras
  • 15,166
  • 7
  • 42
  • 55
  • So i have to manually check if the value has been reverted and set the state back to unchanged? – Hai Long Ng May 18 '20 at 10:37
  • You must work with states, there's no listener to check in real time the old and the actual values you put in. If your state and values are not correct when you try to save you have an exception. – Joe Taras May 18 '20 at 10:39