ef mysql 事务_事务 - EF Core | Microsoft Docs

使用事务Using Transactions

9/26/2020

本文内容

事务允许以原子方式处理多个数据库操作。Transactions allow several database operations to be processed in an atomic manner. 如果已提交事务,则所有操作都会成功应用到数据库。If the transaction is committed, all of the operations are successfully applied to the database. 如果已回滚事务,则所有操作都不会应用到数据库。If the transaction is rolled back, none of the operations are applied to the database.

提示

可在 GitHub 上查看此文章的示例。You can view this article's sample on GitHub.

默认事务行为Default transaction behavior

默认情况下,如果数据库提供程序支持事务,则会在事务中应用对 SaveChanges 的单一调用中的所有更改。By default, if the database provider supports transactions, all changes in a single call to SaveChanges are applied in a transaction. 如果其中有任何更改失败,则会回滚事务且所有更改都不会应用到数据库。If any of the changes fail, then the transaction is rolled back and none of the changes are applied to the database. 这意味着,SaveChanges 可保证完全成功,或在出现错误时不修改数据库。This means that SaveChanges is guaranteed to either completely succeed, or leave the database unmodified if an error occurs.

对于大多数应用程序,此默认行为已足够。For most applications, this default behavior is sufficient. 如果应用程序要求被视为有必要,则应该仅手动控制事务。You should only manually control transactions if your application requirements deem it necessary.

控制事务Controlling transactions

可以使用 DbContext.Database API 开始、提交和回滚事务。You can use the DbContext.Database API to begin, commit, and rollback transactions. 以下示例显示了在单个事务中执行的两个 SaveChanges 操作以及一个 LINQ 查询:The following example shows two SaveChanges operations and a LINQ query being executed in a single transaction:

using var context = new BloggingContext();

using var transaction = context.Database.BeginTransaction();

try

{

context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" });

context.SaveChanges();

context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" });

context.SaveChanges();

var blogs = context.Blogs

.OrderBy(b => b.Url)

.ToList();

// Commit transaction if all commands succeed, transaction will auto-rollback

// when disposed if either commands fails

transaction.Commit();

}

catch (Exception)

{

// TODO: Handle failure

}

虽然所有关系数据库提供程序都支持事务,但在调用事务 API 时,可能会引发其他提供程序类型或不执行任何操作。While all relational database providers support transactions, other providers types may throw or no-op when transaction APIs are called.

保存点Savepoints

备注

EF Core 5.0 中已引入此功能。This feature was introduced in EF Core 5.0.

如果调用 SaveChanges 且事务已在上下文中进行,则在保存任何数据之前,EF 会自动创建保存点。When SaveChang

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值