Sobes.tech
Junior — Middle

How can the transaction isolation level be configured in a database?

sobes.tech AI

Answer from AI

In C#, the transaction isolation level can be configured when creating a TransactionScope object or when using SqlTransaction.

For example, with TransactionScope, you can specify the isolation level through the TransactionOptions parameter:

using System.Transactions;

var options = new TransactionOptions
{
    IsolationLevel = IsolationLevel.Serializable,
    Timeout = TransactionManager.DefaultTimeout
};

using (var scope = new TransactionScope(TransactionScopeOption.Required, options))
{
    // database operations
    scope.Complete();
}

When using SqlTransaction, the isolation level is set at the beginning of the transaction:

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
    try
    {
        // database operations
        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        throw;
    }
}

Thus, the isolation level controls the visibility of changes between transactions and affects locking behavior.