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();
source to share
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
.
source to share