Forcing Entity Framework to run outside of transaction

When using transactions (via TransactionScope) and Entity Framework you might run into a problem when you would like to execute some commands outside of enclosing transaction.

using (var t1 = new TransactionScope()) {
    // ...
    logUsingEF("Done foo"); // Will not be called if an exception is thrown below
    // ...
    t1.Complete();
}

Problem here is that if anything wrong happens (exception), your log won’t be written. A simple solution:

using (var t1 = new TransactionScope()) {
    // ...
    using (var t2 = new TransactionScope(TransactionScopeOption.Suppress)) {
        logUsingEF("Done foo"); // Will always run
        t2.Complete(); // Not required but keep for consistency sake
    }
    // ...
    t1.Complete();
}
Advertisements

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: