Api-PWA/DocuMed.Repository/Repositories/UnitOfWork/UnitOfWork.cs

55 lines
1.8 KiB
C#
Raw Permalink Normal View History

2023-10-10 17:02:38 +03:30
namespace DocuMed.Repository.Repositories.UnitOfWork;
2024-09-28 12:34:36 +03:30
public class UnitOfWork(ApplicationContext applicationContext) : IUnitOfWork
2023-10-10 17:02:38 +03:30
{
private IDbContextTransaction? _currentTransaction ;
public async Task RollBackAsync()
{
if (_currentTransaction == null)
throw new ArgumentNullException(nameof(_currentTransaction));
await _currentTransaction.RollbackAsync();
}
public async Task CommitAsync()
{
if (_currentTransaction == null)
throw new ArgumentNullException(nameof(_currentTransaction));
await _currentTransaction.CommitAsync();
}
public async Task BeginTransaction()
{
2024-09-28 12:34:36 +03:30
_currentTransaction = await applicationContext.Database.BeginTransactionAsync();
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 applicationContext.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 = applicationContext.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;
}
if (entity.State == EntityState.Modified)
{
entity.Property(e => e.ModifiedAt)
.CurrentValue = DateTime.Now;
}
if (entity.State == EntityState.Deleted)
{
entity.Property(e => e.RemovedAt)
.CurrentValue = DateTime.Now;
entity.Property(e => e.IsRemoved)
.CurrentValue = true;
}
}
}
}