我正在编写单元测试(技术上是集成测试,因为我正在连接到数据库)并且我想在测试中的事务中创建记录,并在测试完成后回滚所有数据库修改。我的想法是,我将通过一个 API 调用创建另一个 API 调用期望在数据库中找到的记录。
我有以下有效的代码:
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 之前,事务不会回滚,并且我的测试数据会持久保存到数据库中:
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
最佳答案
来自 the docs (对于 SQL Server compact,但仍然相关):
Implicitly enlisting connections is not supported. To enlist in a transaction scope, you can do the following:
Open a connection in a transaction scope.
Or, if the connection is already opened, call EnlistTransaction method on the connection object.
在第一个示例中,您在事务范围内打开一个连接。在 2nd 你没有入伍。
尝试添加:
cmd.Connection.EnlistTransaction(Transaction.Current);
看看是否有帮助。
关于c# - 使用 MySqlConnector for .NET 是否完全支持 TransactionScope 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1893862/