What is the difference between _context.Entry(entity).State = EntityState.Modified and _context.Entity.Update(entity) in ASP.NET EF Core? For example:
[HttpPut]
public async Task<ActionResult<Student>> PutStudent(Student student)
{
**_context.Entry(student).State = EntityState.Modified;**
await _context.SaveChangesAsync();
return student;
}
[HttpPut]
public async Task<ActionResult<Student>> PutStudent(Student student)
{
**_context.Student.Update(student);**
await _context.SaveChangesAsync();
return student;
}
Setting an entity's state to
Modifiedwill mark all of the entity's scalar properties as modified, meaning thatSaveChangeswill generate an update statement updating all mapped table fields except the key field(s).Not asked, but a single property can also be marked as
Modified:This will also set the entity's state as modified.
The
Updatemethod is quite different, see the docs:This can be very convenient in disconnected scenarios in which new and updated entities are attached to a context. EF will figure out which entities are
Addedand which areModified.Another difference is that the
Updatemethod also traverses nested entities. For example, ifExamsis a collection in theStudentclass, updating aStudentwill also mark itsExamsasModified, orAddedwhere their keys aren't set.Not documented, but worth mentioning, if a
Studentand itsExamsare attached asUnchangedthen theUpdatemethod will only set theStudent's state toModified, not theExams.