我如何加入正在进行的TransactionScope?
如果您使用TransactionScope,您可以创建一个“环境”事务:
using (TransactionScope scope = new TransactionScope())
{
//...stuff happens, then you complete...
// The Complete method commits the transaction.
scope.Complete();
}
Run Code Online (Sandbox Code Playgroud)
那有什么用呢?好吧,.NET 框架中有一些类知道如何通过检查以下内容来检查是否存在环境正在进行的事务static:
这让他们知道有一项交易正在进行中。
例如,如果您有一些不考虑事务的任意数据库操作:
void DropStudents()
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "DROP TABLE Students;";
cmd.ExecuteNonQuery();
}
}
Run Code Online (Sandbox Code Playgroud)
如果你把它放在TransactionScope的中间:
using (TransactionScope scope = new TransactionScope())
{
DropStudents();
// The Complete method commits the transaction.
scope.Complete();
}
Run Code Online (Sandbox Code Playgroud)
突然间,您的 ADO.net 操作处于事务中;并且可以回滚。
SqlClient库知道要检查: …