Created
October 20, 2023 16:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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