Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database.BeginTransaction vs Transactions.TransactionScope [duplicate]

What is the difference between System.Transactions.TransactionScope and EF6's Database.BeginTransaction?

Could someone give a small example or just explain which one to use when with a clear difference?

P.S: In my project, I'm using EF6. I've already read the documentation but it didn't help much. Also looked up the examples but they are rather using SqlConnection.BeginTransaction and now MS has introduced this new Database.BeginTransaction in EF6.

like image 704
Flair Avatar asked Mar 13 '14 15:03

Flair


People also ask

How does Entity Framework handle transactions?

In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes.

Does EF core use transactions by default?

Default transaction behaviorBy default, if the database provider supports transactions, all changes in a single call to SaveChanges are applied in a transaction. If any of the changes fail, then the transaction is rolled back and none of the changes are applied to the database.

What is 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.

What is an ambient transaction?

Ambient TransactionA transaction which automatically identifies a code block that needs to support a transaction without explicitly mentioning any transaction related things. An ambient transaction is not tied just to a database, any transaction aware provider can be used.


1 Answers

I found out the answer in Entity Framework 6's documentation:

With the introduction of EF6, Microsoft recommends to use new API methods: Database.BeginTransaction() and Database.UseTransaction(). Although System.Transactions.TransactionScope is still very well supported, it is no longer necessary for most users of EF6.

While Database.BeginTransaction() is used only for database related operations transaction, System.Transactions.TransactionScope, in addition to that, makes it possible for 'plain C# code' to also be transactional.

Hence, use Database.BeginTransaction() where ever doing only db related operations in a transaction in EF6 otherwise use System.Transactions.TransactionScope for mixing db operations and C# code together in a transaction.

For those who still prefer the TransactionScope approach, it is recommended they checkout its limitations, especially in cloud scenarios (cloud scenarios do not support distributed transactions).

Further information can be found here

like image 65
Flair Avatar answered Nov 08 '22 01:11

Flair