DbContext 更新与 EntityState 修改

DbContext Update vs EntityState Modified

'_context.Entry(entity).State = EntityState.Modified'和'_context.Entity.Update有什么区别ASP.NET EF Core 中的(实体)'?例如:

[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;
}

将实体的状态设置为 Modified 会将实体的所有标量属性标记为已修改,这意味着 SaveChanges 将生成一条更新语句,更新除键之外的所有映射的 table 字段字段。

不问,但单个属性也可以标记为Modified:

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

这也会将实体的状态设置为已修改。

Update方法有很大不同,见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.

这在 断开连接的场景 中非常方便,其中新的和更新的实体附加到上下文。 EF 将找出哪些实体是 Added,哪些是 Modified

另一个区别是Update方法也会遍历嵌套实体。例如,如果 ExamsStudent class 中的集合,更新 Student 也会将其 Exams 标记为 Modified,或者 Added 未设置密钥的地方。

没有记录,但值得一提的是,如果 Student 及其 Exams 附加为 Unchanged,则 Update 方法将仅设置 Student 的状态为 Modified,而不是 Exams