35 lines
1.2 KiB
C#
35 lines
1.2 KiB
C#
using Helpdesk.Domain;
|
|||
|
|
using Microsoft.EntityFrameworkCore;
|
||
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||
|
|
|
||
|
|
namespace Helpdesk.Infrastructure.Persistence;
|
||
|
|
|
||
|
|
/// <summary>Vyplní <c>created_at</c> u nově přidaných entit s <see cref="IHasCreatedAt"/> (kap. 12.4).</summary>
|
||
|
|
internal sealed class CreatedAtInterceptor(TimeProvider clock) : SaveChangesInterceptor
|
||
|
|
{
|
||
|
|
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
|
||
|
|
{
|
||
|
|
Stamp(eventData.Context);
|
||
|
|
return result;
|
||
|
|
}
|
||
|
|
|
||
|
|
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
|
||
|
|
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||
|
|
{
|
||
|
|
Stamp(eventData.Context);
|
||
|
|
return ValueTask.FromResult(result);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Stamp(DbContext? context)
|
||
|
|
{
|
||
|
|
if (context is null)
|
||
|
|
return;
|
||
|
|
|
||
|
|
var now = clock.GetUtcNow().UtcDateTime;
|
||
|
|
foreach (var entry in context.ChangeTracker.Entries<IHasCreatedAt>())
|
||
|
|
{
|
||
|
|
if (entry.State == EntityState.Added)
|
||
|
|
entry.Entity.CreatedAt = now;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|