Entity framework save changes

本秂侑毒 提交于 2019-12-10 13:14:51

问题


Is there a point to save changes after a read only action? The entities are loaded to cache, but nothing changes, should save changes be called before dispose?


回答1:


From doc (DbContext.SaveChanges):

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

No there is no point in calling SaveChanges if you have not made any changes on your context.

You can read more about this in detail 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.



回答2:


You don't need to call SaveChanges() unless you do:

  1. Add
  2. Update
  3. Delete


来源:https://stackoverflow.com/questions/35403667/entity-framework-save-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!