Sobes.tech
Junior — Middle

Wie kann man den Isolationsgrad von Transaktionen in der Datenbank einstellen?

sobes.tech KI

Antwort von AI

In C# kann das Isolationsniveau von Transaktionen beim Erstellen des TransactionScope-Objekts oder bei Verwendung von SqlTransaction eingestellt werden.

Zum Beispiel kann beim TransactionScope das Isolationsniveau über den Parameter TransactionOptions festgelegt werden:

using System.Transactions;

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

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

Bei Verwendung von SqlTransaction wird das Isolationsniveau beim Beginn der Transaktion festgelegt:

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

Auf diese Weise steuert das Isolationsniveau die Sichtbarkeit von Änderungen zwischen Transaktionen und beeinflusst das Verhalten von Sperren.