A question on DBContext.Update in EF Core

Brandon Poindexter 71 Reputation points
2021-08-26T18:31:38.487+00:00

I think I know the answer to this question, but I'd like to get some confirmation.

Let us say I have this code:

var newStudent = new Student();
newStudent.Name = "John Doe";
//set other properties of newStudent
SaveStudent(newStudent);

public void SaveStudent(Student student)
{
  dbContext.Update(student);
  student.Name = "James Doe";
  dbContext.SaveChanges();
}

When I query my database for student records, should I expect to see James Doe and NOT John Doe as the Name property for this record? I believe the answer is yes, because my understanding is that the Update command causes the dbContext to start tracking the entity 'student' and any changes to student after calling Update would be tracked by the DbContext for writing to the database. Do I have this correct?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
711 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Duane Arnold 3,216 Reputation points
    2021-08-27T00:24:30.007+00:00

    The DBconxte.Update sets the object state to modified and trackable within the current DBcontext.

    The subsequent change of the object property to John Doe is set in the object's property will save in the object when SaveChanges() is executed.

    0 comments No comments