Last active
April 29, 2019 11:09
-
-
Save bobdesaunois/5fb219e18d6d83c34cb143c90d66d91a to your computer and use it in GitHub Desktop.
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
public interface ITrackable | |
{ | |
DateTime CreatedAt { get; set; } | |
DateTime UpdatedAt { get; set; } | |
} |
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
public override int SaveChanges(bool acceptAllChangesOnSuccess) | |
{ | |
SetTimestamps(); | |
return base.SaveChanges(acceptAllChangesOnSuccess); | |
} | |
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, | |
CancellationToken cancellationToken = default(CancellationToken)) | |
{ | |
SetTimestamps(); | |
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); | |
} | |
private void SetTimestamps() | |
{ | |
IEnumerable<EntityEntry> entries = | |
ChangeTracker.Entries() | |
.Where(entry => entry.Entity is ITrackable | |
&& (entry.State == EntityState.Added | |
|| entry.State == EntityState.Modified)); | |
foreach (EntityEntry entry in entries) | |
{ | |
var model = (ITrackable)entry.Entity; | |
DateTime now = DateTime.UtcNow; | |
if (entry.State == EntityState.Added) | |
model.CreatedAt = now; | |
model.UpdatedAt = now; | |
} | |
ChangeTracker.Entries() | |
.Where(entry => entry.Entity is ITrackable | |
&& (entry.State == EntityState.Added | |
|| entry.State == EntityState.Modified)); | |
foreach (EntityEntry entry in entries) | |
{ | |
var model = (ITrackable)entry.Entity; | |
DateTime now = DateTime.UtcNow; | |
if (entry.State == EntityState.Added) | |
model.CreatedAt = now; | |
model.UpdatedAt = now; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment