Skip to content

Instantly share code, notes, and snippets.

@bobdesaunois
Last active April 29, 2019 11:09
Show Gist options
  • Save bobdesaunois/5fb219e18d6d83c34cb143c90d66d91a to your computer and use it in GitHub Desktop.
Save bobdesaunois/5fb219e18d6d83c34cb143c90d66d91a to your computer and use it in GitHub Desktop.
public interface ITrackable
{
DateTime CreatedAt { get; set; }
DateTime UpdatedAt { get; set; }
}
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