Api/Brizco.Repository/Repositories/UnitOfWork/UnitOfWork.cs

58 lines
1.9 KiB
C#
Raw Normal View History

using Microsoft.EntityFrameworkCore.Storage;
2023-09-15 12:37:02 +03:30
using Task = System.Threading.Tasks.Task;
namespace Brizco.Repository.Repositories.UnitOfWork;
2024-08-09 21:42:04 +03:30
public class UnitOfWork(ApplicationContext applicationContext) : IUnitOfWork
2023-09-15 12:37:02 +03:30
{
private IDbContextTransaction? _currentTransaction ;
2023-09-15 12:37:02 +03:30
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-08-09 21:42:04 +03:30
_currentTransaction = await applicationContext.Database.BeginTransactionAsync();
}
2023-09-15 12:37:02 +03:30
public async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{
SetAuditables();
2024-08-09 21:42:04 +03:30
await applicationContext.SaveChangesAsync(cancellationToken);
2023-09-15 12:37:02 +03:30
}
private void SetAuditables()
{
2024-08-09 21:42:04 +03:30
IEnumerable<EntityEntry<IApiEntity>> entries = applicationContext.ChangeTracker.Entries<IApiEntity>();
2023-09-15 12:37:02 +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;
}
}
}
}