在 EF Core 2.1 中使用环境事务时是否需要手动关闭 DbConnection?

Do I need to close the DbConnection manually when using ambient transactions with EF Core 2.1?

EF Core 2.1 引入了对环境事务的支持。 sample 创建一个新的 SqlConnection,手动打开它并传递给 DbContext:

using (var scope = new TransactionScope(
    TransactionScopeOption.Required, 
    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
    var connection = new SqlConnection(connectionString);
    connection.Open();

    try
    {
        // Run raw ADO.NET command in the transaction
        var command = connection.CreateCommand();
        command.CommandText = "DELETE FROM dbo.Blogs";
        command.ExecuteNonQuery();

        // Run an EF Core command in the transaction
        var options = new DbContextOptionsBuilder<BloggingContext>()
            .UseSqlServer(connection)
            .Options;

        using (var context = new BloggingContext(options))
        {
            context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" });
            context.SaveChanges();
        }

        // Commit transaction if all commands succeed, transaction will auto-rollback
        // when disposed if either commands fails
        scope.Complete();
    }
    catch (System.Exception)
    {
        // TODO: Handle failure
    }
}

虽然没有调用 connection.Close()

样本中是否缺少这一部分,或者当 TransactionScopeDbContext 被处理时连接是否自动关闭?

编辑:缺少对 Close/Dispose 的调用。。我提交了一个 pull request,现在文档已经更新了。

为了安全使用,使用以便处理连接。

using(var connection = new SqlConnection(connectionString)) {
   ....
}

该行为似乎与环境事务无关,但 谁拥有 DbConnection 问题的答案传递给了 DbContext

EF6 DbContext 接受 DbConnection 的构造函数有 bool contextOwnsConnection 参数用于显式指定。

但是 EF Core 呢?在接受 DbConnection.

UseXyz 方法上没有这样的参数

规则似乎如下,取自UseSqlServer方法connection参数文档:

If the connection is in the open state then EF will not open or close the connection. If the connection is in the closed state then EF will open and close the connection as needed.

我读了"If the passed connection is not opened, EF Core will take the ownership, otherwise the ownership is left to the caller".

由于该示例在 UseSqlServer(connection) 之前调用了 connection.Open();,我假设您对 closing/disposing 它负责,因此我认为该示例不正确。