我目前使用微軟企業庫5.0,我想知道,如果下面的代碼是處理事務的接受的方式回滾多個事務。企業庫:
我已經簡化場景一點,但本質上,我想在同一事務內執行不同的數據庫多個插入。
如果兩個刀片的失敗,所有的交易應該被回滾。
我已經看了TransactionScope
,但我想知道如果我能沒有它管理。
public void InsertStuff_AcrossDbs()
{
//Create a ref to 2 different Db's on the same server
Database db_a = DatabaseFactory.CreateDatabase("Data Source=localhost;Initial Catalog=db_a");
Database db_b = DatabaseFactory.CreateDatabase("Data Source=localhost;Initial Catalog=db_b");
//Create Connections for the 2 db's
using (DbConnection connection_db_a = db_a.CreateConnection())
using (DbConnection connection_db_b = db_b.CreateConnection())
{
//Create DbTransactions for the 2 db's
DbTransaction transaction_dbA = connection_db_a.BeginTransaction();
DbTransaction transaction_dbB = connection_db_b.BeginTransaction();
try
{
//Insert into DbA.Person and get the PK
DbCommand dbCmd_dbA_insert = db_a.GetSqlStringCommand("Insert INTO Person(Name,Age)Values('test',23); SET @pkReturnId= SCOPE_IDENTITY() ");
db_a.AddOutParameter(dbCmd_dbA_insert, "pkReturnId", DbType.Int32, 0);
db_a.ExecuteNonQuery(dbCmd_dbA_insert, transaction_dbA);
int personID = Convert.ToInt32(db_a.GetParameterValue(dbCmd_dbA_insert, "@pkReturnId"));
//Insert 'personId' into dbB.Employee (a different table in a different db)
DbCommand dbCmd_dbB_delete = db_a.GetSqlStringCommand("Insert INTO Employee(personId) VALUES(" + personID + ")");
db_a.ExecuteNonQuery(dbCmd_dbB_delete, transaction_dbB);
//try to commit both transactions
transaction_dbA.Commit();
transaction_dbB.Commit();
}
catch (Exception ex)
{
//If either transactions fails, roll back both
try
{
transaction_dbA.Rollback();
}
catch { }
try
{
transaction_dbB.Rollback();
}
catch { }
throw ex;
}
finally
{
connection_db_a.Close();
connection_db_b.Close();
}
}
}
這段代碼被認爲OK,或者是否會有場景中不是所有的交易都將被回滾,如果他們中的一個應該拋出一個錯誤?