使用MySqlConnector for .NET是否完全支持TransactionScope对象? [英] Is the TransactionScope object fully supported using MySqlConnector for .NET?

查看:102
本文介绍了使用MySqlConnector for .NET是否完全支持TransactionScope对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写单元测试(由于要连接到数据库,因此是技术上的集成测试),我想在测试内的事务中创建记录,并在测试完成后回滚所有数据库修改.我的想法是,我将通过一个API调用创建记录,而另一个API调用希望在数据库中找到该记录.

I'm writing unit tests (technically integration tests since I am connecting to a database) and I want to create records in a transaction within the test, and rollback all database modifications once the test completes. The idea being that I'll create records through one API call that another API call expects to find in the database.

我有以下有效的代码:

string connectionstring = "Server=MyDbServer;Database=MySchema;Uid=MyUser;Pwd=XXX;";
string sql = "Insert Into MyTable (date, Description) VALUES('2009-12-11', 'foo test description');";

 using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
 using (MySqlConnection conn = new MySqlConnection(connectionstring))
 {
       conn.Open();

       using (MySqlCommand cmd = new MySqlCommand(sql, conn))
       {
            cmd.ExecuteNonQuery();
       }
 }

但是,如果我将TransactionScope实例化移动到MySqlCommand之前,则事务不会回滚,并且我的测试数据会持久保存到数据库中:

However, if I move the TransactionScope instantiation to occur just before the MySqlCommand, the transaction is not rolled back, and my test data is persisted to the database:

string connectionstring = "Server=MyDbServer;Database=MySchema;Uid=MyUser;Pwd=XXX;";
string sql = "Insert Into MyTable (date, Description) VALUES('2009-12-11', 'foo test description');";

using (MySqlConnection conn = new MySqlConnection(connectionstring))
{
    conn.Open();

    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
    using (MySqlCommand cmd = new MySqlCommand(sql, conn))
    {
        cmd.ExecuteNonQuery();
    }
}

我想念什么?

注意:MySQL服务器(v.5.0.67-0ubuntu6)托管在Linux计算机上,MySqlConnecter版本为6.1.3

Note: The MySQL server (v. 5.0.67-0ubuntu6) is hosted on a linux machine, MySqlConnecter version is 6.1.3

推荐答案

来自文档(适用于SQL Server Compact,但仍适用):

From the docs (for SQL Server compact, but still relevant):

隐式地征集连接是 不支持.报名参加 交易范围,您可以 以下:

Implicitly enlisting connections is not supported. To enlist in a transaction scope, you can do the following:

在事务中打开连接 范围.

Open a connection in a transaction scope.

或者,如果连接已经存在 打开后,调用EnlistTransaction方法 在连接对象上.

Or, if the connection is already opened, call EnlistTransaction method on the connection object.

在第一个示例中,您正在事务范围中打开连接.在第二个中,您不参加.

In the first example, you are opening a connection in a transaction scope. In the 2nd you are not enlisting.

尝试添加:

cmd.Connection.EnlistTransaction(Transaction.Current);

看看是否有帮助.

这篇关于使用MySqlConnector for .NET是否完全支持TransactionScope对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆