.net mysql transactionscope,使用.NET的MySqlConnector是否完全支持TransactionScope对象?

博客讨论了在进行单元测试时如何在MySQL数据库中使用事务来创建记录,并在测试完成后自动回滚数据。作者遇到的问题是,当TransactionScope实例化的位置改变时,事务无法正常回滚,导致数据持久化到数据库。解决方案涉及到连接对象的EnlistTransaction方法和Transaction.Current的使用。
摘要由CSDN通过智能技术生成

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.

I have the following code that works:

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();

}

}

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();

}

}

What am I missing?

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

解决方案

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.

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.

Try adding:

cmd.Connection.EnlistTransaction(Transaction.Current);

To see if that helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值