使用TransactionScope()进行事务管理

Ama*_*mar 3 .net c# sql-server asp.net

我需要创建一个简单的dotnet应用程序,它将在循环内调用存储过程(存储过程接受几个参数并将它们添加到表中).要求是所有行都插入或非插入.

为了确保这一点,我使用过:

using (TransactionScope scope = new TransactionScope())
{
    foreach (EditedRule editedRules in request.EditedRules)
    {
            ...stored procedure call
    }
}
Run Code Online (Sandbox Code Playgroud)

我以前从未使用TransactionScope过,有人可以告诉我这段代码是否有效,并且我的所有行都会被回滚.

如果有更好的方法,我也将不胜感激.

das*_*ght 5

假设您的存储过程不创建并提交自己的事务,此代码将起作用,只需进行一处更改:您的代码需要scope.Complete()using块结束之前进行编码; 否则,交易将回滚.

using (TransactionScope scope = new TransactionScope()) {
    foreach (EditedRule editedRules in request.EditedRules) {
         ...stored procedure call
    }
    scope.Complete(); // <<== Add this line
}
Run Code Online (Sandbox Code Playgroud)

这个结构背后的想法是Complete只有当块正常退出时才会发生调用,即处理循环时没有异常.如果抛出异常,scope将检测到它,并导致事务回滚.

  • 还要注意隔离级别https://msdn.microsoft.com/en-us/library/ms173763.aspx (2认同)