Created
June 3, 2015 00:51
-
-
Save RhysC/0307d6cf425695cd52d3 to your computer and use it in GitHub Desktop.
Sample Entity Framework (EF) auditable records
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 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