使用 TransactionScope 的过程中,如果存在嵌套事务,比如, Bll 层使用了事务,而所调用的 Dal 内方法也使用了事务的话。假设我们吃掉了 Dal 的异常,那么,外部事务会不会成功?
测试代码如下:
using(var ts = new TransactionScope())
{ foreach(var conn in conns) { conn.Dump(); ExecuteNonQuery(conn, CommandType.Text, "update [EL_Organization].[User] set Name='hhhhhh' where UserName='luminji'",null); try { using(TransactionScope tsInner = new TransactionScope()) { ExecuteNonQuery(conn1, CommandType.Text, "update [EL_Organization].[User] set Name='lll' where UserName='luminji1'",null); throw new Exception(); ExecuteNonQuery(conn2, CommandType.Text, "update [EL_Organization].[User] set Name='lll' where UserName='luminji1'",null); tsInner.Complete(); } } catch { } } ts.Complete(); }
测试发现,TransactionScope 所代表的事务,是会往上抛的,即,内部事务失败,外部也同样失败。
所以,轻易不要吃掉 Dal 层的异常,否则,业务逻辑层的代码执行失败(sql 执行失败),上层没有得到异常,却又不知道为什么发生了异常了。