在多个数据库上实现事务

Uma*_*med 6 .net database sql-server transactions

我正在多个数据库上执行数据更改,我想实现一个涵盖所有更改的事务.

这就是我目前拥有的:

try
{
    db[1].begintransaction();
    db[1].ExecuteNonQuery();

    db[2].begintransaction();
    db[2].ExecuteNonQuery();

    ...

    db[N].begintransaction();
    db[N].ExecuteNonQuery();

    // will execute only if no exception raised during the process
    for (int a = 0; a < N; a++)
    {
        db[a].Commit();// what if there is an error/exception here
    }
}
catch
{
    for (int a = 0; a < N; a++)
    {
        db[a].RollBack();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果在a期间发生异常Commit()(参见评论),上述情况将会非常失败.有没有更好的方法来实现这一目标?

kei*_*en7 12

像这样使用TransactionScope类:

using (TransactionScope ts = new TransactionScope())
{
    //all db code here

    // if an error occurs jump out of the using block and it will dispose and rollback

    ts.Complete();
}
Run Code Online (Sandbox Code Playgroud)

如有必要,TransactionScope类将自动转换为分布式事务.