gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:53:52 27 4
gpt4 key购买 nike

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 调用丢失了。。我提交了拉取请求,文档现在已更新。

最佳答案

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

接受 DbConnection

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

但是 EF Core 呢?在接受 DbConnectionUseXyz 方法上没有这样的参数。

规则好像是这样的,摘自UseSqlServer方法连接参数文档:

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.

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

由于该示例在 UseSqlServer(connection) 之前调用了 connection.Open();,我假设您负责关闭/处置它,因此我会考虑示例不正确。

关于c# - 在 EF Core 2.1 中使用环境事务时是否需要手动关闭 DbConnection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51239326/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com