Unable to access the located object. Deal

We use the Entity Framework and run unit tests within a transaction. At first we got a mistake in the name.

I managed to isolate some kind of problem.

using (TransactionScope scope1 = new TransactionScope())
{
    using (TransactionScope scope2 = new TransactionScope())
    {
           // Here there is no code
    }

    using (Entities se = new Entities())
    {
        EntityConnection entityConnection = (EntityConnection)se.Connection;
        DbConnection storeConnection = entityConnection.StoreConnection;

        storeConnection.Open(); // On this line the error occurs

           // Some code that runs a stored procedure
    }
}

The error we are getting right now is "Operation is not valid for transaction status."

If I delete the transaction area2, everything will be fine.

If I mark area 2 as an external transaction, it also works fine.

+3
source share
2 answers

You create scope2 without an explicit parameter TransactionScopeOptionthat gives a default value TransactionScopeOption.Required; see the Notes section inTransactionScope Constructor

, . , , . .

TransactionScope (scope1), , TransactionScope (scope2) TransactionScopeOption.Required , .

, scope2 , , scope1, , Complete scope2:

,

, , scope2 TransactionScopeOption.RequiresNew ( , .), , scope1 .

. .

+6

, , Scope2 .

, " " ". , , TransactionScopeOption.RequiresNew TransactionScopeOption.Required?

 TransactionOptions rootOptions = new TransactionOptions();
    rootOptions.IsolationLevel = IsolationLevel.ReadCommitted;
    OtherObject.Scope2 = new TransactionScope(TransactionScopeOption.Required, rootOptions);

    TransactionOptions options = new TransactionOptions();
    options.IsolationLevel = IsolationLevel.ReadCommitted;
    options.Timeout = getTransactionTimeout();
    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
                {

                                .............
                    scope.Complete();
                }
0

Source: https://habr.com/ru/post/1715979/


All Articles