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

61 lines
2.1 KiB
C#
Raw Normal View History

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