1. The EF encapsulates the transaction: the SaveChange () of the context is transactional.
2. Operations that rely on multiple different context (that is, distributed operations) or multiple calls to the context.savechanges () operation are separated from the EF transaction encapsulation and can be implemented using TransactionScope. Case on behalf of:
[CSharp]View Plaincopy
- using (TransactionScope scope = new TransactionScope ())
- {
- //do something with Context1
- //do something with Context2
- //save and discard changes
- Context1. SaveChanges ();
- //save and discard changes
- Context2. SaveChanges ();
- //if We get here things is looking good.
- Scope.complete ();
- }
But it is risky to write, if Context1. SaveChanges () succeeded, context2. SaveChanges () fails and terminates when Scope.complete () commits the transaction, and CONTEXT1 has successfully executed a requirement that may not necessarily be met. If you need to context1, context2 or not succeed at the same time, or not successful, you need to make a small adjustment to the code, such as the following code:
[CSharp]View Plaincopy
- using (TransactionScope scope = new TransactionScope ())
- {
- //do something with Context1
- //do something with Context2
- //save Changes but don ' t discard yet
- Context1. SaveChanges (false);
- //save Changes but don ' t discard yet
- Context2. SaveChanges (false);
- //if We get here things is looking good.
- Scope.complete ();
- Context1. AcceptAllChanges ();
- Context2. AcceptAllChanges ();
- }
Using SaveChanges (false) to first send the necessary database Operations command to the database, it is important to note that CONTEXT1 and context2 have not really changed, if the transaction terminates, automatic rollback, both of the changes are not actually committed to the database, so it can be successfully rolled back.
TransactionScope's understanding:
1. Not only in database transactions, but also other types of transactions can be managed, the function is very powerful, poor performance
2. You should use the same context for database operations as much as possible, for reasons:
Saving resources and not creating a context is a resource-intensive operation.
Using the same context in different Dal can also achieve transactional purposes, so TransactionScope is not necessary in general database transactions
Resources
Http://www.cnblogs.com/aisini/archive/2011/03/25/1994487.html
A preliminary understanding of transaction processing in EF