I have a class with two methods, MethodA and MethodB. They both use Entity Framework Core to make changes to a database. External code can call any of these methods. If MethodA is called, it will do changes to the database, but it will also call MethodB.
In MethodB, a transaction is used to make sure all or none of the database changes are committed.
I want to have a transaction in MethodA as well, and I want to have that transaction include both the database changes made in MethodA and those made in MethodB.
Here's some code (some error handling etc. omitted):
public async Task MethodA(MyDbContext dbContext)
{
await using var transaction = dbContext.Database.BeginTransactionAsync();
try
{
// [DO CHANGES TO THE DATABASE]
await dbContext.SaveChangesAsync();
await MethodB(dbContext);
await transaction.CommitAsync();
}
catch (Exception ex)
{
await transaction.RollbackAsync();
}
return true;
}
public async Task MethodB(MyDbContext dbContext)
{
await using var transaction = dbCOntext.Database.BeginTransactionAsync();
try
{
// [DO CHANGES TO THE DATABASE]
await dbContext.SaveChangesAsync();
await transaction.CommitAsync();
}
catch (Exception ex)
{
await transaction.RollbackAsync();
}
return true;
}
It seems to me like there will be two transactions when calling MethodA, and I want to make sure that if I do a rollback in MethodA, the changes made in MethodB will also be rolled back.
Is there a way to use the same transaction in both methods, but still allow MethodB to have its own transaction if the method is called directly from external code (not from MethodA)?
The database is in Microsoft SQL Server.