When the Attach method exists, where are we forced to use the Update method?
For example
public void UpdateStudent(Student student)
{
var student = _context.Students.FirstOrDefault(s => s.Id == student.Id);
student.FullName = student.FullName;
student.Age = student.Age;
context.Students.Update(student); //or context.Students.Attach(student) ?
context.SaveChanges();
}
Sina Miri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Attach begins tracking the given entity and entries reachable from the given entity but will start its state as Unchanged
even if you object is different from that of the one in the database.
Update will do the same thing, but starts with a state of Modified
.
var entity = context.Students.Attach(student);
entity.State = EntityState.Modified;
is the same as
context.Students.Update(student);
In your example if you do attach after making the changes the SaveChanges
call will not result in any changes being saved to the database as no changes were made after attaching. You would have to attach, and then make changes.