The use of SaveChanges() in Entity Framework is very frequent, and calling SaveChanges() after a single modification or deletion of data returns the number of impact records.
To use batch modification or batch deletion of data, you need the SaveChanges(false)+AcceptAllChanges() method.
SaveChanges(false) is just a notification that EF needs to perform an operation on the database, which is pending in memory and can be undone when necessary, such as AcceptAllChange() committing is truly successful, and EF will undo the operation of SaveChanges(false).
When dealing with distributed transaction operations, it is necessary to use TransactionScope to handle it, and many times we will write like this:
But writing like this is risky, false For example, context1. SaveChanges() succeeded, context2. SaveChanges() is problematic, we are in scope. Complete() will terminate when the transaction is committed, and Context1 has been successfully executed
(In my practice, the above can actually be rolled back normally, if context1. SaveChanges() succeeded, context2. SaveChanges() is problematic, neither will be executed successfully! Reference the using System.Transaction namespace in your project. Defining a TransactionScope in using is equivalent to defining a scope of things, i.e., the scope of this transaction is within using. In the using scope, if there is no scope. Complete() command, then the scope will automatically roll back all operations when destroyed. ) This may not necessarily meet our needs. If we need context1 and context2 to be executed successfully at the same time, or neither succeeds, we need to make small adjustments to the code, such as using the following code:
We use SaveChanges(false) to send the necessary database operation commands to the database first, which is to note that context1 and context2 have not really changed, if the transaction is terminated and automatically rolled back, neither change is actually committed to the database, so it can be successfully rolled back.
|