Api-PWA/DocuMed.Repository/Repositories/Base/RepositoryWrapper.cs

65 lines
2.4 KiB
C#
Raw Permalink Normal View History

2023-10-10 17:02:38 +03:30
namespace DocuMed.Repository.Repositories.Base;
2024-09-28 12:34:36 +03:30
public class RepositoryWrapper(ApplicationContext context, ICurrentUserService currentUserService)
: IRepositoryWrapper
2023-10-10 17:02:38 +03:30
{
private IDbContextTransaction? _currentTransaction;
2024-09-28 12:34:36 +03:30
public IBaseRepository<T> SetRepository<T>() where T : ApiEntity => new BaseRepository<T>(context, currentUserService);
2023-10-10 17:02:38 +03:30
public async Task RollBackAsync(CancellationToken cancellationToken)
{
if (_currentTransaction == null)
throw new ArgumentNullException(nameof(_currentTransaction));
await _currentTransaction.RollbackAsync(cancellationToken);
}
public async Task CommitAsync(CancellationToken cancellationToken)
{
if (_currentTransaction == null)
throw new ArgumentNullException(nameof(_currentTransaction));
await _currentTransaction.CommitAsync(cancellationToken);
}
public async Task BeginTransaction(CancellationToken cancellationToken)
{
2024-09-28 12:34:36 +03:30
_currentTransaction = await context.Database.BeginTransactionAsync(cancellationToken);
2023-10-10 17:02:38 +03:30
}
public async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{
SetAuditables();
2024-09-28 12:34:36 +03:30
await context.SaveChangesAsync(cancellationToken);
2023-10-10 17:02:38 +03:30
}
private void SetAuditables()
{
2024-09-28 12:34:36 +03:30
IEnumerable<EntityEntry<IApiEntity>> entries = context.ChangeTracker.Entries<IApiEntity>();
2023-10-10 17:02:38 +03:30
foreach (EntityEntry<IApiEntity> entity in entries)
{
if (entity.State == EntityState.Added)
{
entity.Property(e => e.CreatedAt)
.CurrentValue = DateTime.Now;
2024-09-28 12:34:36 +03:30
if (currentUserService.UserName != null)
2023-10-24 12:45:25 +03:30
entity.Property(e => e.CreatedBy)
2024-09-28 12:34:36 +03:30
.CurrentValue = currentUserService.UserName;
2023-10-10 17:02:38 +03:30
}
if (entity.State == EntityState.Modified)
{
2023-10-24 12:45:25 +03:30
if (!entity.Property(e => e.IsRemoved).CurrentValue)
{
entity.Property(e => e.ModifiedAt)
.CurrentValue = DateTime.Now;
2024-09-28 12:34:36 +03:30
if (currentUserService.UserName != null)
2023-10-24 12:45:25 +03:30
entity.Property(e => e.ModifiedBy)
2024-09-28 12:34:36 +03:30
.CurrentValue = currentUserService.UserName;
2023-10-24 12:45:25 +03:30
}
2023-10-10 17:02:38 +03:30
}
}
}
public void Dispose()
{
_currentTransaction?.Dispose();
2024-09-28 12:34:36 +03:30
context?.Dispose();
2023-10-10 17:02:38 +03:30
}
}