Junior — Middle
Will the data in the database be updated after calling the SaveChanges method following retrieval of an object from the database?
sobes.tech AI
Answer from AI
The SaveChanges method in Entity Framework updates the data in the database based on changes made to tracked objects.
If you retrieved an object from the database through the context, changed its properties, and called SaveChanges, the changes will be saved to the database.
Example:
using(var context = new MyDbContext())
{
var user = context.Users.First(); // get object from database
user.Name = "New Name"; // change property
context.SaveChanges(); // save changes to database
}
If you did not change the object or did not track changes, calling SaveChanges will not update data.
Thus, data in the database will only be updated if the object was changed and those changes are tracked by the context before calling SaveChanges.