Entity Framework: SaveChanges()和AcceptAllChanges()方法

SaveChanges()方法用于将对象中的数据保存至数据库并将对象追踪状态复位。在交易操作中,如果保存数据产生异常,该方法将取消交易。
AcceptAllChanges()方法接受数据保存结果并修改对象状态。对于增加和修改的对象,状态改变为Unchanged,对于删除的对象状态改变为Detached。
如果调用了SaveChanges()方法而未使用AcceptAllChangesAfterSave,则必须调用AcceptAllChanges()方法。在交易操作中,如果允许用户在交易失败后重试,AcceptAllChanges()方法是非常有用的。
 

Call AcceptAllChanges() to accepts the changes on all associated entries in the ObjectStateManager so their resultant state is either unchanged or detached.

This method iterates all the ObjectStateEntry objects within the ObjectStateManager that are Added or Modified, and then sets the state of the entry to Unchanged. The Deleted items become detached.

SaveChanges() persists all updates to the data source and resets change tracking in the object context. It operates within a transaction. SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.

If the SaveChanges method was called and the AcceptAllChangesAfterSave was not specified, the user must call the AcceptAllChanges method. The AcceptAllChanges method is useful in the scenario where a transaction has failed and a user wants to retry.

Reference: http://msdn.microsoft.com

posted on 2014-04-04 06:11  橡皮鱼  阅读(773)  评论(0编辑  收藏  举报