Files
hrynco-notification-service/HrynCo.NotificationService.DAL.EF/Core/EfUnitOfWork.cs
T
Anatolii Grynchuk c2a4f3b9d7 fix: inherit EF entities from Entity base class
- TemplateEntity, ProviderEntity, ProviderUsageEntity now inherit Entity (from DAL.Abstract)
- Removes duplicated Id, Created, Updated properties from each entity

Ref: IT-628

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-01 23:27:38 +03:00

100 lines
2.4 KiB
C#

using HrynCo.NotificationService.DAL.Abstract;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
namespace HrynCo.NotificationService.DAL.EF.Core;
internal abstract class EfUnitOfWork<TDbContext> : IUnitOfWork
where TDbContext : DbContext
{
private readonly TDbContext _context;
private EfTransactionAdapter? _currentTransaction;
protected EfUnitOfWork(TDbContext context)
{
_context = context;
}
public async Task<ITransaction> BeginTransactionAsync(CancellationToken cancellationToken = default)
{
if (_currentTransaction != null)
{
return _currentTransaction;
}
IDbContextTransaction tx = await _context.Database.BeginTransactionAsync(cancellationToken);
_currentTransaction = new EfTransactionAdapter(tx);
return _currentTransaction;
}
public ITransaction? GetCurrentTransaction()
{
return _currentTransaction;
}
public async Task ExecuteInTransactionAsync(Func<Task> action)
{
ITransaction? existing = GetCurrentTransaction();
bool ownsTransaction = existing is null;
ITransaction tx = existing ?? await BeginTransactionAsync();
try
{
await action();
if (ownsTransaction)
{
await tx.CommitAsync();
}
}
catch
{
if (ownsTransaction)
{
await tx.RollbackAsync();
}
throw;
}
finally
{
if (ownsTransaction)
{
await tx.DisposeAsync();
}
}
}
public async Task<TResult> ExecuteInTransactionAsync<TResult>(Func<Task<TResult>> action)
{
ITransaction? existing = GetCurrentTransaction();
bool ownsTransaction = existing is null;
ITransaction tx = existing ?? await BeginTransactionAsync();
try
{
TResult result = await action();
if (ownsTransaction)
{
await tx.CommitAsync();
}
return result;
}
catch
{
if (ownsTransaction)
{
await tx.RollbackAsync();
}
throw;
}
finally
{
if (ownsTransaction)
{
await tx.DisposeAsync();
}
}
}
}