在transactionscope中记录数据库失败

时间:2014-02-28 19:02:31

标签: c# ado.net transactionscope

我尝试用我的程序做以下事情。 创建一个新的transactioncope,执行insert命令进行日志记录,执行不同的命令进行更新,然后故意抛出异常。

正如我所期望的那样,回滚更新命令,但是如何提交insert命令?看来insert命令也回滚了,但我想提交记录记录。

我不使用也不想要MSDTC。

class Program
{
    private static string connectString1 = "myconnstring";
    static void Main(string[] args)
    {

        try
        {
            var opt = new TransactionOptions
            {
                IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
                Timeout = TransactionManager.MaximumTimeout
            };

            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, opt))
            {
                using (SqlConnection conn = new SqlConnection(connectString1))
                {
                    conn.Open();

                    Logging(conn);

                    SqlCommand command1 = new SqlCommand("update Company set City='BP' where Id = 2", conn);
                    int aff = command1.ExecuteNonQuery();
                    throw null;
                }
                scope.Complete();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Message: {0}", ex.Message);
        }
    }

    public static void Logging(SqlConnection conn)
    {
        var opt = new TransactionOptions
        {
            IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
            Timeout = TransactionManager.MaximumTimeout
        };
        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress, opt))
        {
            SqlCommand command2 = new SqlCommand("insert into ErrorLog(AppURL,Title,Message) values ('a','b','c')", conn);
            int aff2 = command2.ExecuteNonQuery();
            scope.Complete();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

似乎我没有传入现有连接,但是我在压缩范围内创建了一个新连接,那么即使外部事务被回滚,也会保留日志插入....

    public static void Logging()
    {
        var opt = new TransactionOptions
        {
            IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
            Timeout = TransactionManager.MaximumTimeout
        };
        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress, opt))
        {
            using (SqlConnection conn2 = new SqlConnection(connectString1))
            {
                conn2.Open();
                SqlCommand command2 = new SqlCommand("insert into ErrorLog(AppURL,Title,Message) values ('a','b','c')", conn2);
                int aff2 = command2.ExecuteNonQuery();
                scope.Complete();
            }
        }
    }