简体   繁体   English

实体框架保存更改

[英]Entity framework save changes

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? 实体被加载到缓存,但没有任何变化,应该在处置之前保存更改吗?

From doc ( DbContext.SaveChanges ) : 来自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. 如果您没有对上下文进行任何更改,则调用SaveChanges没有任何意义。

You can read more about this in detail here 您可以详细阅读更多关于这个这里

An entity can be in one of five states as defined by the EntityState enumeration. 实体可以处于由EntityState枚举定义的五种状态之一中。 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 已删除:实体正在被上下文跟踪并存在于数据库中,但在下次调用SaveChanges时已标记为从数据库中删除
  • Detached: the entity is not being tracked by the context 已分离:上下文未跟踪实体

SaveChanges does different things for entities in different states: SaveChanges为不同状态的实体做了不同的事情:

  • Unchanged entities are not touched by SaveChanges. SaveChanges不会触及未更改的实体。 Updates are not sent to the database for entities in the Unchanged state. 对于处于Unchanged状态的实体,不会向数据库发送更新。
  • Added entities are inserted into the database and then become Unchanged when SaveChanges returns. 添加的实体将插入到数据库中,然后在SaveChanges返回时变为Unchanged。
  • Modified entities are updated in the database and then become Unchanged when SaveChanges returns. 修改后的实体在数据库中更新,然后在SaveChanges返回时变为Unchanged。
  • Deleted entities are deleted from the database and are then detached from the context. 已删除的实体将从数据库中删除,然后从上下文中分离。

除非你这样做,否则你不需要调用SaveChanges()

  1. Add
  2. Update
  3. Delete

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM