15c58522ef
- replace EfRepository/BaseDbContext/UtcValueConverter with BaseEfRepository and BaseRepository - add IEfRepository interface hierarchy - consolidate IEntity into Entity.cs, remove standalone IEntity.cs - add PagedResult - adjust all namespaces to HrynCo.DAL.Abstract / HrynCo.DAL.EF - add README.md with solution overview, versioning rules, class diagram - add AGENTS.md Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
103 lines
2.4 KiB
C#
103 lines
2.4 KiB
C#
namespace HrynCo.DAL.EF.Core;
|
|
|
|
using HrynCo.DAL.Abstract;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Storage;
|
|
|
|
public 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 transaction = await _context.Database.BeginTransactionAsync(cancellationToken);
|
|
_currentTransaction = new EfTransactionAdapter(transaction);
|
|
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();
|
|
}
|
|
}
|
|
}
|
|
|
|
public ITransaction? GetCurrentTransaction()
|
|
{
|
|
return _currentTransaction;
|
|
}
|
|
}
|