EF Core Transactions Example

visibility 110 access_time 9 months ago languageEnglish

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.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

timeline Stats
Page index 0.43
More from Kontext
SQLite in .NET Core with Entity Framework Core
visibility 55,278
thumb_up 3
access_time 2 years ago
EntityFramework Core - Connect to MySQL
visibility 126
thumb_up 0
access_time 2 years ago