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

Dan*_*zka 3 c# transactionscope entity-framework-core

EF Core 2.1引入了对环境事务的支持.该示例创建一个新的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
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然没有电话connection.Close().

样品中是否缺少此部件,或者当处理TransactionScopeDbContext处理时,连接是否以某种方式自动关闭?

编辑:要关闭呼叫/处置丢失.我提交了拉取请求,文档现在已更新.

Iva*_*oev 8

这种行为似乎与环境交易无关,但问题的答案是谁拥有DbConnection传递给aDbContext.

EF6 DbContext构造函数接受DbConnection具有bool contextOwnsConnection显式指定的参数.

但是EF Core怎么样?UseXyz方法接受时没有这样的参数DbConnection.

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

如果连接处于打开状态,则EF将不会打开或关闭连接.如果连接处于关闭状态,则EF将根据需要打开和关闭连接.

我读到"如果传递的连接没有打开,EF Core将取得所有权,否则所有权留给调用者".

由于connection.Open();之前调用的示例UseSqlServer(connection),我假设您负责关闭/处理它,因此我认为该示例不正确.