ADO.Net Subscriber Transactions

I want to ask how to properly use transactions in ADO.Net Entity Framework (call, rollback, commit)? I have this code but it gives me an exception

"Invalid operation. The connection is closed." 

      

(In this code, NorthwindEntities inherit "DBContext")

NorthwindEntities context = new NorthwindEntities();
DbTransaction tran = context.Database.Connection.BeginTransaction();
var cust = context.Customers.FirstOrDefault(x => x.CustomerID == "BOLID");
cust.Country = "Nigeria";
context.SaveChanges();
tran.Rollback();

      

+3


source to share


2 answers


To commit a transaction in EF, just call context.SaveChanges()

.

Internally, it SaveChanges

opens a connection, starts a db transaction, pushes all pending changes tracked by the context into the store, commits a transaction, and drops the connection. If an error occurs while saving the changes, the db transaction is rolled back.

To undo a "transaction" simply drop the context instance.



There is usually no need to use external db transactions with EF.

Note that I am using "transaction" in quotes because the EF tracker for changing context is not the equivalent of a db transaction. When you make some changes to the data tracked by the context, those changes don't immediately affect the store. They are expected until you name SaveChanges

.

+6


source


EF has a TransactionScope analogue of the native db transaction. TransactionScope works in your application layer but behaves similar to db transactions and is supported internally by EF)



0


source







All Articles