Trusted answers to developer questions

TransactionScope with multiple databases in C#

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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();
}

To read more, check out the official docs.

RELATED TAGS

c#
transaction
database
sql
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?