最近碰到一個場景:在Entity Framework保存錯誤的時候,須要將該錯誤記錄在DB中。由於DB在savechange的時候會繼續保存以前的數據,因此一直會報錯,沒法保存錯誤日誌。spa
這就須要實現一個取消修改的功能,網上找了下,實現方法見下:日誌
public void RejectChanges() { foreach (var entry in ChangeTracker.Entries()) { switch (entry.State) { case EntityState.Modified: case EntityState.Deleted: entry.State = EntityState.Modified; //Revert changes made to deleted entity. entry.State = EntityState.Unchanged; break; case EntityState.Added: entry.State = EntityState.Detached; break; } } }
見:https://stackoverflow.com/questions/16437083/dbcontext-discard-changes-without-disposingcode