In Entity Framework (EF), transaction management usually only requires the least manual operation. By passing FALSE to SaveChanges (), the framework will be established or participated in transactions. After the successful execution, AcceptAllChanges () will submit and complete the changes in the transaction.
However, some scenarios may benefit from using SaveChanges (FALSE) and Acceptallchanges () at the same time. Their main advantage is that it involves a distributed affairs that involves multiple contexts.
Consider the following code of code:
If Context1.SaveChanges () fails to successfully executes, Context2.SaveChanges () fails, the entire distributed transaction will be suspended. Unfortunately, EF has discarded changes in Context1 and cannot recover or effectively record errors.
<code>using (TransactionScope scope = new TransactionScope()) { // 对 context1 执行操作 // 对 context2 执行操作 // 保存并丢弃更改 context1.SaveChanges(); // 保存并丢弃更改 context2.SaveChanges(); // 如果执行到这里,则一切看起来都很正常。 scope.Complete(); }</code>
In order to solve this problem, please use the following modified methods:
This modification allows only the two contexts to submit their changes only after the transaction is successful. If abnormalities occur, the change will be kept in the ObjectStateManager above and below for further processing, such as retry or record logs.
<code>using (TransactionScope scope = new TransactionScope()) { // 对 context1 执行操作 // 对 context2 执行操作 // 保存更改,但不要立即丢弃 context1.SaveChanges(false); // 保存更改,但不要立即丢弃 context2.SaveChanges(false); // 如果执行到这里,则一切看起来都很正常。 scope.Complete(); context1.AcceptAllChanges(); context2.AcceptAllChanges(); }</code>
Therefore, SaveChaanges (FALSE) and Acceptallchanges () provide greater flexibility in distributed transaction scenarios, which can repair and record logs when faulty.
The above is the detailed content of SaveChanges(false) and AcceptAllChanges() in EF: When Should You Use Them for Distributed Transactions?. For more information, please follow other related articles on the PHP Chinese website!