在 EntityFramework Core 的同一事务中使用 ExecuteSqlCommand 和 SavesChanges

mab*_*ead 5 entity-framework-core

我正在解决 MySql/EF Core 的一个问题,我随机抛出一个异常说Nested transactions are not supported. 当我的系统仅由一个用户使用时,不会发生此异常。但是当我并行运行我的测试或当我有多个用户时,就会发生异常。我查看了所有代码,它们无法创建嵌套事务。

到目前为止,唯一让我感到害怕的代码如下:

using (var transaction = _context.Database.BeginTransaction())
{
    // Create a few entities and add them to the EF context
    ...

    // Insert the rows: hopefully at this point, my transaction is not commited yet.
    _context.SaveChanges();

    // I then want to update a few rows with a raw sql statement without 
    // having to load the entities in memory.   
    _context.Database.ExecuteSqlCommand("UPDATE ...");

    // Now that I have inserted and inserted some data, I want to commit all these 
    // changes atomically.
    transaction.Commit();
}
Run Code Online (Sandbox Code Playgroud)

这安全吗?我能保证我的 SaveChanges 和 ExecuteSqlCommand 将在同一个 MySqlConnection 上执行吗?我有一种感觉,当我调用 SaveChanges 时,它会关闭我的连接并将其放回连接池中。然后,我的 ExecuteSqlCommand 从池中获取一个新连接(它可能是相同的或另一个)。所以我的初始连接(我打开事务的那个)被放回池中,它可以被另一个线程重用。

这只是一种预感,我完全不确定这是否会导致问题。

最后我真正的问题是:

  • 在事务中使用 SaveChanges 和 ExecuteSqlCommand 是否安全?

mab*_*ead 3

我从 MySql.Data.EntityFrameworkCore/MySql.Data 6.10.1-beta 升级到 6.10.3-rc,看起来问题已经消失了。由于问题是随机的,我不能完全确定问题确实已解决,但到目前为止还不错。

编辑: 3年后,这个问题再也没有被观察到。