SaveChanges vs. AcceptAllChanges in Entity Framework

前端 未结 2 437
庸人自扰
庸人自扰 2020-12-18 19:10

What\'s the difference between, _context.SaveChanges and _context.AcceptAllChanges(), is the AcceptAllChanges() is sort of reloading d

2条回答
  •  失恋的感觉
    2020-12-18 19:47

    ObjectContext.AcceptAllChanges Method - MSDN

    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.

    You may see this: http://blogs.msdn.com/b/alexj/archive/2009/01/11/savechanges-false.aspx

    If you call SaveChanges() or SaveChanges(true),the EF simply assumes that if its work completes okay, everything is okay, so it will discard the changes it has been tracking, and wait for new changes.

    Unfortunately though if something goes wrong somewhere else in the transaction, because the EF discarded the changes it was tracking, we can’t recover.

    This is where SaveChanges(false) and AcceptAllChanges() come in.

    SaveChanges(false) tells the EF to execute the necessary database commands, but hold on to the changes, so they can be replayed if necessary.

    Now if the broader transaction fails you can retry the EF specific bits, with another call to SaveChanges(false). Alternatively you can walk through the state-manager to log what failed.

    Once the broader transaction succeeds, you simply call AcceptAllChanges() manually, and the changes that were being tracked are discarded.

提交回复
热议问题