Skip to content

Instantly share code, notes, and snippets.

@RhysC
Created June 3, 2015 00:51
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 RhysC/0307d6cf425695cd52d3 to your computer and use it in GitHub Desktop.
Save RhysC/0307d6cf425695cd52d3 to your computer and use it in GitHub Desktop.
Sample Entity Framework (EF) auditable records
public class YourApplicationDbContextBase : DbContext
{
//...
public override int SaveChanges()
{
var changeSet = ChangeTracker.Entries<IAuditable>();
if (changeSet != null)
SetAuditDetails(changeSet);
return base.SaveChanges();
}
protected static void SetAuditDetails(IEnumerable<DbEntityEntry<IAuditable>> changeSet)
{
var utcNowAuditDate = DateTime.UtcNow;
foreach (var dbEntityEntry in changeSet)
{
switch (dbEntityEntry.State)
{
case EntityState.Added:
dbEntityEntry.Entity.CreatedOn = utcNowAuditDate;
dbEntityEntry.Entity.ModifiedOn = utcNowAuditDate;
break;
case EntityState.Modified:
dbEntityEntry.Entity.ModifiedOn = utcNowAuditDate;
break;
}
}
}
//...
}
public interface IAuditable
{
DateTimeOffset CreatedOn { get; set; }
DateTimeOffset ModifiedOn { get; set; }
}
public class MyAuditableEntity : IAuditable
{
public Guid Id { get; set; }
//other properties
public DateTimeOffset CreatedOn { get; set; }
public DateTimeOffset ModifiedOn { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment