0
Azure

TransactionScope in Azure

Multi-database applications
The TransactionScope class establishes an ambient transaction in .NET. (An “ambient transaction” is one that lives in the current thread.) All connections opened within the TransactionScope participate in the transaction. If different databases participate, the transaction is automatically elevated to a distributed transaction. The outcome of the transaction is controlled by setting the scope to complete to indicate a commit.

Snippet

using (var scope = new TransactionScope())
{
using (var conn1 = new SqlConnection(connStrDb1))
{
conn1.Open();
SqlCommand cmd1 = conn1.CreateCommand();
cmd1.CommandText = string.Format(“insert into T1 values(1)”);
cmd1.ExecuteNonQuery();
}

using (var conn2 = new SqlConnection(connStrDb2))
{
conn2.Open();
var cmd2 = conn2.CreateCommand();
cmd2.CommandText = string.Format(“insert into T2 values(2)”);
cmd2.ExecuteNonQuery();
}

scope.Complete();
}

Sharded database applications
Elastic database transactions for SQL DB also support coordinating distributed transactions where you use the OpenConnectionForKey method of the elastic database client library to open connections for a scaled out data tier. Consider cases where you need to guarantee transactional consistency for changes across several different sharding key values. Connections to the shards hosting the different sharding key values are brokered using OpenConnectionForKey.

Snippet
using (var scope = new TransactionScope())
{
using (var conn1 = shardmap.OpenConnectionForKey(tenantId1, credentialsStr))
{
conn1.Open();
SqlCommand cmd1 = conn1.CreateCommand();
cmd1.CommandText = string.Format(“insert into T1 values(1)”);
cmd1.ExecuteNonQuery();
}

using (var conn2 = shardmap.OpenConnectionForKey(tenantId2, credentialsStr))
{
conn2.Open();
var cmd2 = conn2.CreateCommand();
cmd2.CommandText = string.Format(“insert into T1 values(2)”);
cmd2.ExecuteNonQuery();
}

scope.Complete();
}

 

Ref:Microsoft

No Comments

    Leave a Reply