Blog

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.

Environment:
Visual Studio 2012 / C# / Entity Framework 5.0

Solutions:

  1. Override the function SaveChanges(SaveOptions options) of ObjectContext
  2. Validate the state of each entity in the context before SaveChangesObjectStateEntry entry in   z          Context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
  3. if entry.State == EntityState.Added then
    discard ModifiedDate, set CreatedDate to current date time
  4. if entry.State == EntityState.Modified then
    discard CreatedDate, set ModifiedDate to current date time
  5. Call base.SaveChanges(options)