2013-10-11 54 views
-1

他我只是想知道,在實體框架中當我們調用savechages()函數時,它比較實體中的當前值和原始值並更新數據庫。那是對的嗎?。我還有一個疑問,如果上述條件是正確的,有什麼需要在創建操作中調用savechanges()?。我們爲什麼要在創建操作中調用它。SaveChanges函數在實體框架的CRUD操作中

www.google.com 

回答

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.