69 lines
1.6 KiB
C#
69 lines
1.6 KiB
C#
using Microsoft.EntityFrameworkCore.Storage;
|
|
|
|
namespace GamificationService.Database.UnitOfWork;
|
|
|
|
public class UnitOfWork : IUnitOfWork
|
|
{
|
|
#region Fields
|
|
private readonly ApplicationContext _context;
|
|
private IDbContextTransaction? _transaction;
|
|
|
|
#endregion
|
|
|
|
public UnitOfWork(ApplicationContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
#region Repositories
|
|
#endregion
|
|
|
|
#region Save Methods
|
|
public bool SaveChanges() => _context.SaveChanges() > 0;
|
|
|
|
public async Task<bool> SaveChangesAsync() => (await _context.SaveChangesAsync()) > 0;
|
|
#endregion
|
|
|
|
#region Transactions
|
|
public async Task BeginTransactionAsync()
|
|
{
|
|
if (_transaction is not null)
|
|
throw new InvalidOperationException("A transaction has already been started.");
|
|
|
|
_transaction = await _context.Database.BeginTransactionAsync();
|
|
}
|
|
|
|
public async Task CommitTransactionAsync()
|
|
{
|
|
if (_transaction is null)
|
|
throw new InvalidOperationException("A transaction has not been started.");
|
|
|
|
try
|
|
{
|
|
await _transaction.CommitAsync();
|
|
}
|
|
catch
|
|
{
|
|
await RollbackTransactionAsync();
|
|
throw;
|
|
}
|
|
finally
|
|
{
|
|
await _transaction.DisposeAsync();
|
|
_transaction = null;
|
|
}
|
|
}
|
|
|
|
public async Task RollbackTransactionAsync()
|
|
{
|
|
if (_transaction is null)
|
|
return;
|
|
|
|
await _transaction.RollbackAsync();
|
|
await _transaction.DisposeAsync();
|
|
_transaction = null;
|
|
}
|
|
#endregion
|
|
|
|
}
|