簡體   English   中英

在使用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引入了對環境事務的支持。 示例創建一個新的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是否以某種方式自動關閉連接?

編輯:要關閉呼叫/處置失蹤 我提交了拉取請求,文檔現在已更新。

該行為似乎與環境事務無關,但擁有DbConnection的問題的答案傳遞給DbContext

接受DbConnection DbContext構造函數具有bool contextOwnsConnection參數,用於顯式指定。

但是EF Core怎么樣? UseXyz方法接受DbConnection沒有這樣的參數。

該規則似乎如下,取自UseSqlServer方法connection參數文檔:

如果連接處於打開狀態,則EF將不會打開或關閉連接。 如果連接處於關閉狀態,則EF將根據需要打開和關閉連接。

我讀到“如果傳遞的連接沒有打開,EF Core將取得所有權,否則所有權留給調用者”

由於該示例調用connection.Open(); UseSqlServer(connection)之前,我假設你負責關閉/處理它,所以我認為這個例子是不正確的。

使用安全裝置以便連接處理。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM