EF Core Transactions Example
Database transaction is used to process multiple actions in an atomic manner (ACID). In Entity Framework or EF Core, SaveChanges will perform all changes in one transaction if the database supports that. You can also use DbContext.Database.BeginTransaction method to initiate a transaction.
Code snippet
The following code snippet creates a customer and account in one transaction. If the account creation fails, the transaction will be rolled back automatically. There is no explicit transaction rollback as it uses using statement which will dispose the transaction object.
using var context = new ApplicationDbContext(); using var transaction = context.Database.BeginTransaction(); try { var customer = new Customer(Name="A Customer"); context.Customers.Add(customer); await context.SaveChangesAsync(); var account = new Account(OpenDate = DateTime.Now, CustomerID = customer.ID); context.Accounts.Add(account); await context.SaveChangesAsync(); transaction.Commit(); } catch (Exception) { }
copyright
This page is subject to Site terms.
comment Comments
No comments yet.
Log in with external accounts
warning Please login first to view stats information.
article
SQLite in .NET Core with Entity Framework Core
article
Resolve the Issues in Upgrading Entity Framework to Version 6.1
article
The Entity Framework tools version '3.1.7' is older than that of the runtime '5.0.3'.
article
Entity Framework Core Code-First - Generate Covering Index with Columns Included
article
EntityFramework Core: Generate Migration Scripts in a Separate Project
Read more (15)