Api/Berizco.Repository/Repositories/UnitOfWork/UnitOfWork.cs

47 lines
1.4 KiB
C#

using Microsoft.EntityFrameworkCore.ChangeTracking;
using Task = System.Threading.Tasks.Task;
namespace Brizco.Repository.Repositories.UnitOfWork;
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationContext _applicationContext;
public UnitOfWork(ApplicationContext applicationContext)
{
_applicationContext = applicationContext;
}
public async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{
SetAuditables();
await _applicationContext.SaveChangesAsync(cancellationToken);
}
private void SetAuditables()
{
IEnumerable<EntityEntry<IApiEntity>> entries = _applicationContext.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;
}
if (entity.State == EntityState.Deleted)
{
entity.Property(e => e.RemovedAt)
.CurrentValue = DateTime.Now;
entity.Property(e => e.IsRemoved)
.CurrentValue = true;
}
}
}
}