refactor: modernized GenericRepository and UnitOfWork with newer code from Roma
This commit is contained in:
16
Database/UnitOfWork/IUnitOfWork.cs
Normal file
16
Database/UnitOfWork/IUnitOfWork.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
|
||||
namespace GamificationService.Database.UnitOfWork;
|
||||
|
||||
public interface IUnitOfWork
|
||||
{
|
||||
#region Repositories
|
||||
#endregion
|
||||
|
||||
#region Methods
|
||||
bool SaveChanges();
|
||||
Task<bool> SaveChangesAsync();
|
||||
Task BeginTransactionAsync();
|
||||
Task CommitTransactionAsync();
|
||||
Task RollbackTransactionAsync();
|
||||
#endregion
|
||||
}
|
||||
68
Database/UnitOfWork/UnitOfWork.cs
Normal file
68
Database/UnitOfWork/UnitOfWork.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
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
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user