Entity framework 保存更改

Entity framework save changes

只读操作后是否需要保存更改?实体已加载到缓存,但没有任何变化,是否应在处置之前调用保存更改?

来自doc (DbContext.SaveChanges)

Saves all changes made in this context to the underlying database.

不,如果您没有对上下文进行任何更改,则调用 SaveChanges 没有任何意义。

您可以详细阅读此内容here

An entity can be in one of five states as defined by the EntityState enumeration. These states are:

  • Added: the entity is being tracked by the context but does not yet exist in the database
  • Unchanged: the entity is being tracked by the context and exists in the database, and its property values have not changed from the values in the database
  • Modified: the entity is being tracked by the context and exists in the database, and some or all of its property values have been modified
  • Deleted: the entity is being tracked by the context and exists in the database, but has been marked for deletion from the database the next time SaveChanges is called
  • Detached: the entity is not being tracked by the context

SaveChanges does different things for entities in different states:

  • Unchanged entities are not touched by SaveChanges. Updates are not sent to the database for entities in the Unchanged state.
  • Added entities are inserted into the database and then become Unchanged when SaveChanges returns.
  • Modified entities are updated in the database and then become Unchanged when SaveChanges returns.
  • Deleted entities are deleted from the database and are then detached from the context.

您不需要调用 SaveChanges(),除非您这样做:

  1. Add
  2. Update
  3. Delete