Home > other >  DbContext Update vs EntityState Modified
DbContext Update vs EntityState Modified

Time:03-25

What are 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;
}

CodePudding user response:

Setting an entity's state toModified will mark all of the entity's scalar properties as modified, meaning that SaveChanges will 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:

_context.Entry(student).Property(s => s.Name).IsModified = true;

This will also set the entity's state as modified.

The Update method is quite different, see the docs:

Begins tracking the given entity (...)
For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Modified state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure new entities will be inserted, while existing entities will be updated. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.

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 Added and which are Modified.

Another difference is that the Update method also traverses nested entities. For example, if Exams is a collection in the Student class, updating a Student will also mark its Exams as Modified, or Added where their keys aren't set.

Not documented, but worth mentioning, if a Student and its Exams are attached as Unchanged then the Update method will only set the Student's state to Modified, not the Exams.

  • Related