Skip to content

Instantly share code, notes, and snippets.

@codemonkey85
Created October 20, 2023 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codemonkey85/3f1b524727742bfa90b33218c1c8d55c to your computer and use it in GitHub Desktop.
Save codemonkey85/3f1b524727742bfa90b33218c1c8d55c to your computer and use it in GitHub Desktop.
My approach to saving created / updated timestamps and user ID with Entity Framework Core in .NET
private void DatabaseContext_SavingChanges(object? sender, SavingChangesEventArgs e)
{
if (sender is not DatabaseContext dbContext)
{
return;
}
AddTimeStamps(dbContext.ChangeTracker, DateTime.UtcNow);
}
private void AddTimeStamps(ChangeTracker changeTracker, DateTime dateTime)
{
foreach (var entityEntry in changeTracker.Entries())
{
if (entityEntry.Entity is not BaseEntity baseEntity)
{
continue;
}
switch (entityEntry.State)
{
case EntityState.Added:
baseEntity.DateCreated = dateTime;
if (_tenantId is not null)
{
baseEntity.CreatedByUserId = _tenantId;
}
break;
case EntityState.Modified:
baseEntity.DateCreated ??= baseEntity.DateUpdated = dateTime;
if (_tenantId is not null)
{
baseEntity.CreatedByUserId ??= baseEntity.UpdatedByUserId = _tenantId;
}
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment