Entity Framework取消修改
最近碰到一个场景:在Entity Framework保存错误的时候,需要将该错误记录在DB中。因为DB在savechange的时候会继续保存之前的数据,所以一直会报错,无法保存错误日志。
这就需要实现一个取消修改的功能,网上找了下,实现方法见下:
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-disposing