TransactionScope with multiple databases in C#

TransactionScope is a class that was introduced in .NET 2.02.0 and allows you to implement transactions at an application level (in C#).

In databases, a transaction is a single unit of work. It consists of multiple statements like INSERT or UPDATE and follows the ACID rule.

ACID rule: either all statements are committed and the transaction is successful, or all are canceled and the transaction fails.

TransactionScope is part of the System.Transaction namespace in the .NET framework.

svg viewer

Code

Here is an example of connecting with two SQL databases in C#. The transaction below is also called a distributed transaction, as it involves multiple databases.

TransactionScope ensures that all statements either commit or rollback without the developer worrying about the ACID rule.

// TransactionScope guarantees both commands will either commit
// or rollback as a single unit of work.
using (TransactionScope scope = new TransactionScope())
{
using (conn1 = new SqlConnection(connString1))
{
conn1.Open();
// Statement 1
// Statement 2
// ...
// If we reach here, means that above statements succeded.
using (conn2 = new SqlConnection(connString2))
{
conn2.Open();
// Statement 1
// Statement 2
// ...
}
}
scope.Complete();
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved