How to Make Entity Created and Modified DateTimestamp Consistent
In business application, it is critical to make the time stamp consistent for all entities. However, developers sometimes may not following the process well.
To make the date time stamp consistent, we handle the created and modified date time in a central location before saving data to database.
Visual Studio 2012 / C# / Entity Framework 5.0
- Override the function SaveChanges(SaveOptions options) of ObjectContext
- Validate the state of each entity in the context before SaveChangesObjectStateEntry entry in z Context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
- if entry.State == EntityState.Added then
discard ModifiedDate, set CreatedDate to current date time
- if entry.State == EntityState.Modified then
discard CreatedDate, set ModifiedDate to current date time
- Call base.SaveChanges(options)