0

I have an utility method creating TransactionScope in my application.

I want to do a unit test to validate that the returned TransactionScope has the correct IsolationLevel set, to be sure that nobody can modify the code without breaking the tests.

System.Transactions.Transaction scope does not have public properties exposing information like that. (http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx)

Any way to get this information?

4

1 回答 1

2

您可以运行 SQL 查询来检查隔离级别:

SELECT CASE transaction_isolation_level 
WHEN 0 THEN 'Unspecified' 
WHEN 1 THEN 'ReadUncomitted' 
WHEN 2 THEN 'Readcomitted' 
WHEN 3 THEN 'Repeatable' 
WHEN 4 THEN 'Serializable' 
WHEN 5 THEN 'Snapshot' END AS IsolationLevel 
FROM sys.dm_exec_sessions 
where session_id = @@SPID

编辑

根据下面的评论,还有一种方法可以从代码中获取隔离级别。这可能是这样的:

using (TransactionScope scope = new TransactionScope())
{
    using (SqlConnection connection1 = new SqlConnection("Data Source=localhost;Integrated Security=True"))
    {
        Transaction trans = Transaction.Current;
        System.Transactions.IsolationLevel level = trans.IsolationLevel;
    }
}

您可以通过调用获取当前交易Transaction.Current

来源:使用事务范围实现隐式事务

于 2013-09-30T21:13:50.377 回答