ASP.NET CORE Using Transactions
2018-01-30 00:00
706 查看
Default transaction behavior
By default, if the database provider supports transactions, all changes in a single call toSaveChanges()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. This means that
SaveChanges()is guaranteed to either completely succeed, or leave the database unmodified if an error occurs.
Controlling transactions
You can use theDbContext.DatabaseAPI to begin, commit, and rollback transactions. The following example shows two
SaveChanges()operations and a LINQ query being executed in a single transaction.
Not all database providers support transactions. Some providers may throw or no-op when transaction APIs are called.
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 } } }
相关文章推荐
- First ASP.NET Core Application on a Mac Using Visual Studio Code
- Using MongoDB with Web API and ASP.NET Core
- Using Custom Domains With IIS Express In Asp.Net Core
- [转]ASP.NET Core 1.0: Using Entity Framework Core 1.0 - Transaction
- [转]An introduction to OAuth 2.0 using Facebook in ASP.NET Core
- Real-time chart using ASP.NET Core and WebSocket
- [转]Using NLog for ASP.NET Core to write custom information to the database
- ASP.NET Core 1.0: Using Entity Framework Core
- ASP.NET Core Building chat room using WebSocket
- ASP.NET Core 1.0: Using Entity Framework Core 1.0 - Transaction
- ASP.NET之Using用法
- 用ASP.NET Core 1.0中实现邮件发送功能
- 用ASP.NET Core 2.0 建立规范的 REST API -- GET 和 POST
- asp.net core 2.0 Microsoft.Extensions.Logging 文本文件日志扩展
- ASP.NET Core 静态文件及JS包管理器(npm, Bower)的使用
- ASP.NET Core轻松入门之Configure中IHostingEnvironment和IApplicationLifetime的使用
- ASP.NET Core开发-使用Nancy框架
- ASP.NET Core Web App应用第三方Bootstrap模板的方法教程
- ASP.NET Core开发之HttpContext
- Asp.Net Core 项目实战之权限管理系统(3) 通过EntityFramework Core使用PostgreSQL