SaveChanges函数在实体框架的CRUD操作中

时间:2013-10-11 03:59:18

标签: entity-framework

他只是要知道,在实体框架中,当我们调用savechages()函数时,它会比较实体中的当前值和原始值并更新数据库。那是对的吗?。我还有一个疑问,如果上述条件正确,是否需要在create operation中调用savechanges()?为什么我们在创建操作中调用它。

 www.google.com

1 个答案:

答案 0 :(得分:1)

您对SaveChanges()it check if the entity is in modified state所说的真实,然后保存更改,以便它们可以反映在数据库中。

如果是创建操作create a new object and add that to your entity。再次entity state is modified所以你也需要在这里调用savechanges()。

SaveChanges()

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.