【问题标题】:Why Is TransactionScope Not Working With Sqlite?为什么 TransactionScope 不能与 Sqlite 一起使用?
【发布时间】: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


    【解决方案1】:

    经过进一步研究,我相信答案是——在撰写本文时,Microsoft.Data.Sqlite 不支持 TransactionScope。这是打开的 GitHub 项目:

    https://github.com/dotnet/efcore/issues/13825

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 2018-03-09
      • 2012-10-09
      • 2020-03-18
      • 2017-11-21
      • 2019-04-11
      • 2012-09-19
      相关资源
      最近更新 更多