Auto-generated timestamp in Entity Manager

I have a WPF DataGrid binding to some objects (Entity Framework 4+).

The user then edits the DataGrid and clicks SAVE. Then the data is saved back to MS SQL Server 2008 using SaveChanges() . Well ... now, I would like to have an AUTOMATIC timestamp that stores the time of the last change and automatically updates.

Guys, is this possible? How?

Thanks James

+4
source share
1 answer

The simplest solution for this is at the database level:

  • Create a new column in the table to save the DateTime value.
  • Create a database trigger to set a column for each insert or update in the table.
  • Match the new column as a property in your entity
  • Set StoreGeneratedPattern for the new Computed property so that the value generated in the database is correctly updated to your attached object after each insert or update.

If you do not like the trigger, you must do it manually to override SaveChanges, where you will find all the objects that will be inserted or updated, and set the column:

 public override int SaveChanges(SaveOptions options) { var entities = ObjectStateManger.GetObjectStateEntries(EntityState.Added | EntityState.Modified) .Select(e => e.Entity) .OfType<YourEntityType>(); DateTime now = DateTime.Now; foreach(var entity in entities) { entity.Updated = now; } return base.SaveChanges(options); } 
+6
source

All Articles