3

I'm working with a system using Entity Framework, and I'm wrapping a call in a TransactionScope but only because I want to set the IsolationLevel as ReadUncommited (basically doing NOLOCK, as described in one of the answers here). This is only a query, no changes to any data.

using (var scope = new TransactionScope(TransactionScopeOption.Required,
                        new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
    List<T> toReturn = query.ToList();
    scope.Complete();
    return toReturn;
}

My understanding is that calling Complete() is like doing a SQL commit. What happens if I don't call scope.Complete()? This is just a database query so there's nothing to commit.

Community
  • 1
  • 1
Mike G
  • 133
  • 1
  • 7

2 Answers2

1

If you don't call complete, your transactions within the scope will be rolled back. Complete you have to call explicitly. You don't have to call Rollback if you don't want to.

https://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.complete(v=vs.110).aspx

Yatrix
  • 13,361
  • 16
  • 48
  • 78
1

You must do that.The Complete method commits the transaction. If an exception has been thrown,Complete is not called and the transaction is rolled back.

When you are satisfied that all operations within the scope are completed successfully, you should call this method only once to inform that transaction manager that the state across all resources is consistent, and the transaction can be committed. It is very good practice to put the call as the last statement in the using block. Failing to call this method aborts the transaction, because the transaction manager interprets this as a system failure, or exceptions thrown within the scope of transaction. However, you should also note that calling this method does not guarantee a commit of the transaction. It is merely a way of informing the transaction manager of your status. After calling this method, you can no longer access the ambient transaction via the Current property, and trying to do so results in an exception being thrown.

Sampath
  • 63,341
  • 64
  • 307
  • 441