0

I have the following code:

var scopeOption = TransactionScopeOption.RequiresNew;
var transactionOptions = new TransactionOptions
{
    IsolationLevel = IsolationLevel.ReadUncommitted
};
using (new TransactionScope(scopeOption, transactionOptions))
{
    var context = new ObjectContext("connection string");
    context.Connection.Open(); // <-- This line throws
}

It throws the following exception:

System.Data.EntityException: The underlying provider failed on Open.
Caused by: System.Data.SqlClient.SqlException, MSDTC on server 'xxxx' is unavailable.

But it only throws the exception the on the first attempt to open the connection. Any subsequent calls to the example code work perfectly and don't try to contact the DTC.

Note: Changing scopeOption to TransactionScopeOption.Suppress seems to fix the issue, and as I'm not performing any writes to the database is more than acceptable.

Can anybody think of why opening the first (and only) connection in a brand-new TransactionScope would cause a DTC escalation only the first time the code is invoked?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
iggymoran
  • 4,059
  • 2
  • 21
  • 26
  • Did you validate that all subsequent `Open()` aren't just no-ops? The connection is already open, from the first 'failed' attempt. – Remus Rusanu Sep 16 '14 at 12:51
  • @RemusRusanu, this was the simplest bit of code I could get to fail. In my "real" code I actually execute a query and the Open method is invoked by EF, not me. For example, I'd do something like context.CreateObjectSet().Where(...).ToList(); – iggymoran Sep 16 '14 at 12:54
  • My point is that is not the 'first' Open that has the issue, but any 'true' Open. The exception is thrown after the connection is opened, when System.Transaction attempts to enroll into DTC. – Remus Rusanu Sep 16 '14 at 12:56
  • For a more lengthy discussion on the topic, see [TransactionScope automatically escalating to MSDTC on some machines](http://stackoverflow.com/questions/1690892/transactionscope-automatically-escalating-to-msdtc-on-some-machines) – Remus Rusanu Sep 16 '14 at 12:59
  • What I still don't understand is why this only happens the first time this method is invoked. The second time, the query (or open) executes successfully and returns the results I'd expect. – iggymoran Sep 16 '14 at 13:03

1 Answers1

0

In case anybody ever has this issue, the only way I got this to work was to change the code so the creation of the context happens outside the transaction scope.

var scopeOption ...
var transactionOptions ...

var context = new ObjectContext("connection string");
using (new TransactionScope(scopeOption, transactionOptions))
{
    context.OpenConnection();
    //do other stuff here with the context.
}
iggymoran
  • 4,059
  • 2
  • 21
  • 26