How do I utilize Entity Framework transactions?

entity-framework transactions


When you have code like this:

Something something = new Something();
BlahEntities b = new BlahEntities()    

how do run that addition inside a transaction?

6/28/2009 2:03:58 PM

Accepted Answer

You can place your code within a Transaction scope

using(TransactionScope scope = new TransactionScope())
    // Your code
    scope.Complete(); //  To commit.

TransactionScope is in the System.Transactions namespace which is located in the assembly of the same name (which you may need to add manually to your project).

6/28/2009 3:06:38 PM

Popular Answer

The ObjectContext has a connection property that you can use to manage transactions.

using (var context = new BlahEntities())
using (var tx = context.BeginTransaction())
    // do db stuff here...

In the case of an exception the transaction will be rolled back. Because the call to BeginTransaction() requires and open connection it makes sense to wrap the call to BeginTransaction possibly in an extension method.

public static DbTransaction BeginTransaction(this ObjectContext context)
    if (context.Connection.State != ConnectionState.Open)
    return context.Connection.BeginTransaction();

One scenario where I believe this approach could be useful over TransactionScope, is when you have to access two datasources and only need transactional control over one of the connections. I think that in that case the TransactionScope will promote to a distributed transaction which might not be requiered.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow