我正在使用Entity Framework Core(7)開發控制台應用程序。

該應用程序分為3個不同的區域,但數據庫是共享的。我創建了3個不同的DbContext ,現在我需要在它們之間執行一個事務。所以我需要一個原子操作來保存所有的更改或什麼都沒有(回滾)。

我知道在實體frameowrk 6中有一個名為TransactionScope的類,但我無法在EF Core中找到一個替代。

使用以下代碼:

public static void Main(string[] args)
    {
        var options = new DbContextOptionsBuilder<DbContext>()
        .UseSqlServer(new SqlConnection("Server=x.x.x.x,1433;Database=test;user id=test;password=test;"))
        .Options;

        var cat = new Cat { Name = "C", Surname = "C", Age = 55 };
        var dog = new Dog { Date = DateTime.Now, Code = 120, FriendId = cat.Id };


        using (var context1 = new DogsContext(options))
        {
            using (var transaction = context1.Database.BeginTransaction())
            {
                try
                {
                    context1.Dogs.Add(dog);
                    context1.SaveChanges();

                    using (var context2 = new CatsContext(options))
                    {
                        context2.Database.UseTransaction(transaction.GetDbTransaction());
                        context2.Cats.Add(cat);
                    }

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    transaction.Rollback();
                }
            }
        }
    }

我收到以下錯誤:

System.InvalidOperationException: ExecuteScalar requires the command to have a transaction when the connection assigned to the co
mmand is in a pending local transaction.  The Transaction property of the command has not been initialized.
   at System.Data.SqlClient.SqlCommand.ValidateCommand(Boolean async, String method)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStrea
m, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteScalar()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMe
thod, IReadOnlyDictionary`2 parameterValues, Boolean openConnection, Boolean closeConnection)
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)

一般承認的答案

TransactionScope不是Entity Framework的一部分。它是System.Transactions命名空間的一部分。此外,TransactionScope不是處理Entity Framework 6.x事務的推薦方法

使用Entity Framework Core,您只能在關係數據庫的多個上下文之間共享事務。

更多信息請訪問: https//docs.microsoft.com/en-us/ef/core/saving/transactions

示例(未測試):

        using (var context1 = new YourContext())
        {
            using (var transaction = context1.Database.BeginTransaction())
            {
                try
                {
                    // your transactional code
                    context1.SaveChanges();

                    using (var context2 = new YourContext())
                    {
                        context2.Database.UseTransaction(transaction.GetDbTransaction());
                        // your transactional code
                    }

                    // Commit transaction if all commands succeed, transaction will auto-rollback when disposed if either commands fails
                    transaction.Commit();
                }
                catch (Exception)
                {
                    // handle exception
                }
            }
        }


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow