简体   繁体   中英

ADO.Net Entity Framework Transactions

I want to ask which is the right way to use transactions in ADO.Net Entity Framework (call,rollback,commit) ? I have this code, but this give me 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();

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

Internally, SaveChanges opens a connection, starts a db transaction, pushes all pending changes, tracked by the context, to the store, commits transaction and disposes connection. If there was any error during saving changes, db transaction being rolled back.

To rollback "transaction", just throw away context instance.

Usually, there's no need to use external db transactions with EF.

Note, that I'm using "transaction" in quotes, because EF context's change tracker isn't an equivalent of db transaction. When you make some changes with data, tracked by context, that changes don't affect store immediately. They are pending, until you call SaveChanges .

EF has TransactionScope an analogue of native db transaction. TransactionScope works on you application layer, but behaves similarly to db transactions and supported by EF internals)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM