How to configure transactions in Entity Framework?

How do I set up transactions in Entity Framework 4? In a simple old Ado.Net, we had a class called SqlTransaction, we could also specify the isolation level for this transaction, such as Read_Committed, Read_UnCommitted, etc. I can not find all of these options in the Entity Framework. How can we customize them?

+4
source share
1 answer

You can use the TransactionScope class and set the isolation level using TransactionOptions , as described here :

Some of the overloaded TransactionScope constructors adopt a structure of type TransactionOptions to indicate the level of isolation in addition to the timeout value. By default, a transaction is executed with the isolation level set to Serializable. Choosing a isolation level other than Serializable is typically used for high-access systems. This requires a deep understanding of the theory of transaction processing and the semantics of the transaction itself, the concurrency problems associated with it, and the implications for system consistency.

For instance:

using (var context = new EFTestEntities()) { context.AddToProducts(new Product { Name = "Widget" }); context.AddToProducts(new Product { Name = "Chotchky" }); TransactionOptions options = new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted, Timeout = TransactionManager.DefaultTimeout }; using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options)) { // do any EF work that you want to be performed in the transaction context.SaveChanges(); // commit the transaction scope.Complete(); } } 
+6
source

Source: https://habr.com/ru/post/1345335/


All Articles