Api/Netina.Repository/Repositories/Base/RepositoryWrapper.cs

62 lines
2.2 KiB
C#
Raw Normal View History

2024-08-09 21:55:16 +03:30
using Microsoft.EntityFrameworkCore.ChangeTracking;
2024-02-12 22:01:15 +03:30
using Microsoft.EntityFrameworkCore.Storage;
2024-04-16 20:01:34 +03:30
namespace Netina.Repository.Repositories.Base;
2024-08-09 21:55:16 +03:30
public class RepositoryWrapper(ApplicationContext context, ICurrentUserService currentUserService)
: IRepositoryWrapper
2023-12-16 20:25:12 +03:30
{
private IDbContextTransaction? _currentTransaction;
2024-08-09 21:55:16 +03:30
public IBaseRepository<T> SetRepository<T>() where T : ApiEntity => new BaseRepository<T>(context, currentUserService);
2023-12-16 20:25:12 +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-08-09 21:55:16 +03:30
_currentTransaction = await context.Database.BeginTransactionAsync(cancellationToken);
2023-12-16 20:25:12 +03:30
}
public async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{
SetAuditables();
2024-08-09 21:55:16 +03:30
await context.SaveChangesAsync(cancellationToken);
2023-12-16 20:25:12 +03:30
}
private void SetAuditables()
{
2024-08-09 21:55:16 +03:30
IEnumerable<EntityEntry<IApiEntity>> entries = context.ChangeTracker.Entries<IApiEntity>();
2023-12-16 20:25:12 +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;
2024-08-09 21:55:16 +03:30
if (currentUserService.UserName != null)
2023-12-16 20:25:12 +03:30
entity.Property(e => e.ModifiedBy)
2024-08-09 21:55:16 +03:30
.CurrentValue = currentUserService.UserName;
2023-12-16 20:25:12 +03:30
}
}
}
public void Dispose()
{
_currentTransaction?.Dispose();
2024-08-09 21:55:16 +03:30
context?.Dispose();
2023-12-16 20:25:12 +03:30
}
}