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()
though.
示例中是否缺少此部分,或者连接是否在连接时以某种方式自动关闭TransactionScope
or the DbContext
被处置?
编辑:调用 Close/Disposewas丢失的。我提交了拉取请求,文档现已更新。
该行为似乎与环境交易无关,但问题的答案谁拥有DbConnection
传递给一个DbContext
.
EF6 DbContext
构造函数接受DbConnection
has bool contextOwnsConnection
参数来明确指定。
但是 EF Core 怎么样?上没有这个参数UseXyz
方法接受DbConnection
.
该规则似乎如下,取自UseSqlServer method connection
参数文档:
如果连接处于打开状态,则 EF 将不会打开或关闭连接。如果连接处于关闭状态,则 EF 将根据需要打开和关闭连接。
我读过的“如果传递的连接未打开,EF Core 将取得所有权,否则所有权将留给调用者”.
由于该示例调用了connection.Open();
before UseSqlServer(connection)
,我假设您负责关闭/处置它,所以我认为该示例是不正确的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)