From f6d5733992b7b0554f3001a987700f69062d5118 Mon Sep 17 00:00:00 2001 From: Kevin Matsubara Date: Mon, 14 Apr 2025 21:49:44 +0200 Subject: [PATCH] Add example with transaction security with save points. --- EntityFrameworkCore.Console/Program.cs | 50 ++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/EntityFrameworkCore.Console/Program.cs b/EntityFrameworkCore.Console/Program.cs index bb07364..2ddd15e 100644 --- a/EntityFrameworkCore.Console/Program.cs +++ b/EntityFrameworkCore.Console/Program.cs @@ -23,6 +23,56 @@ context.Database.EnsureCreated(); // var firstCoach = await context.Coaches.FirstOrDefaultAsync(); +async Task TransactionWithSavepoint() +{ + var transaction = context.Database.BeginTransaction(); + + var league = new League + { + Name = "Geosphere league" + }; + + context.Add(league); + context.SaveChanges(); + + transaction.CreateSavepoint("CreatedLeague"); + + var coach = new Coach + { + Name = "Brad Ironfist" + }; + + context.Add(coach); + context.SaveChanges(); + + var teams = new List + { + new Team + { + Name = "Dominators", + LeagueId = league.Id, + CoachId = coach.Id + } + }; + + context.AddRange(teams); + context.SaveChanges(); + + try + { + transaction.Commit(); + } + catch (Exception) + { + // Rollback everything. + //transaction.Rollback(); + + // Or rollback to a specific save point. + transaction.RollbackToSavepoint("CreatedLeague"); + throw; + } +} + async Task UserDefinedQuery() { var earliestMatch = context.GetEarliestTeamMatch(1);