[英]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()
。
這個部分是否在示例中丟失,或者在TransactionScope
或DbContext
是否以某種方式自動關閉連接?
編輯:要關閉呼叫/處置失蹤 。 我提交了拉取請求,文檔現在已更新。
該行為似乎與環境事務無關,但擁有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.