【发布时间】:2021-06-14 06:38:30
【问题描述】:
总之,下面的代码创建一个新表,启动一个 TransactionScope,向新表中插入一行,退出 TransactionScope 而不在 TransactionScope 上调用 Complete,然后获取新表中的行数。我希望行数为零,因为当 TransactionScope 在没有调用 Complete 的情况下退出时,插入应该已经回滚。事实上,代码报告的行数为 1。当我针对 Sql Server 数据库运行代码时,我确实得到了预期的零行数,所以我认为代码过程是正确的。
我正在使用 v5.0.4 的 Microsoft.Data.Sqlite NuGet 包并针对 .NET Framework v4.8 进行编码。
为什么对Sqlite数据库执行代码时插入没有回滚?
class Program
{
static void Main(string[] args)
{
string dbPath = @".\MyDb.db";
using (SqliteConnection connection = new SqliteConnection($"Data Source = {dbPath}"))
{
connection.Open();
using (SqliteCommand command = connection.CreateCommand())
{
command.CommandText = @"DROP TABLE IF EXISTS TestTable;CREATE TABLE TestTable (TestCol TEXT);";
command.ExecuteNonQuery();
}
}
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
{
using (SqliteConnection connection = new SqliteConnection($"Data Source = {dbPath}"))
{
connection.Open();
using (SqliteCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO TestTable(TestCol) VALUES('Row 1')";
command.ExecuteNonQuery();
}
}
//ts.Complete();
}
using (SqliteConnection connection = new SqliteConnection($"Data Source = {dbPath}"))
{
connection.Open();
using (SqliteCommand command = connection.CreateCommand())
{
command.CommandText = @"SELECT COUNT(*) FROM TestTable;";
Console.WriteLine($"Row count is {command.ExecuteScalar()}");
}
}
Console.Read();
}
}
【问题讨论】:
标签: .net sqlite transactionscope