问题
Based on this article here as well as the question: Difference Between Transaction and TransactionScope we know that TransactionScope
The TransactionScope class provides a simple way to mark a block of code as participating in a transaction, without requiring you to interact with the transaction itself. A transaction scope can select and manage the ambient transaction automatically. Due to its ease of use and efficiency, it is recommended that you use the TransactionScope class when developing a transaction application.
Whereas System.Transactions.Transaction
The Transaction class contains methods used by developers implementing resource managers for enlistment. It also provides functionalities for cloning a transaction and controlling the current transaction context.
The question here is whether there is a way to chose which of the two to use. The obvious answer is to use implicit transactions if you have no reason to use explicit, but what would that reason be?
Are the explicit transactions there, only to support legacy implementations?
回答1:
Looking around various resources, I stumbled to the following which partially answers my question: Working with transactions in EF 6
Based on this documentation (which is mostly based on EF but limitations seem to apply anyway):
There are still some limitations to the TransactionScope approach:
Requires .NET 4.5.1 or greater to work with asynchronous methods.
- It cannot be used in cloud scenarios unless you are sure you have one and only one connection (cloud scenarios do not support distributed transactions).
- It cannot be combined with the Database.UseTransaction() approach of the previous sections.
- It will throw exceptions if you issue any DDL and have not enabled distributed transactions through the MSDTC Service.
Advantages of the TransactionScope approach:
- It will automatically upgrade a local transaction to a distributed transaction if you make more than one connection to a given database or combine a connection to one database with a connection to a different database within the same transaction (note: you must have the MSDTC service configured to allow distributed transactions for this to work).
- Ease of coding. If you prefer the transaction to be ambient and dealt with implicitly in the background rather than explicitly under you control then the TransactionScope approach may suit you better.
Being that the first article is no longer supported and the EF 6 article is newer + the comment from @MarcGravell, I assume that the decision comes down to the advantages and disadvantages of the EF 6 article above.
来源:https://stackoverflow.com/questions/59717075/c-sharp-system-transactions-vs-transactionscope