问题
I am trying to use transactions with EF4 Code-first with an unit of work implementation. Is there a reason we cannot use Connection.BeginTransaction from the context ? It is only intended to be used in SQL transactions only ? Because when im calling it i get the error : Illegal operation. Connection is closed.
Thanks.
回答1:
Part of the answer will be that DbContext.SaveChanges() is automatically transactional, so in many cases, you will not need to roll your own transactions. What is your scenario, and why do you think that you need to manually do transactions?
If you decide you need them, wrap SaveChanges in a transaction:
using (TransactionScope transaction = new TransactionScope())
{
context.SaveChanges();
}
If you run Profiler, you will note that the transaction is rolled back once you leave the using{} block. To commit your transaction, call transaction.Complete(); after SaveChanges().
来源:https://stackoverflow.com/questions/4939405/connection-begintransaction-and-entity-framework-4