1

I have an entity class (using model first, if that matters) that should persist its own last change date.

Is there a way to update this on saving? Right now I have only found overriding OnPropertyChanged but that is not the right override, as it is also called when loading the object.

Residuum
  • 11,878
  • 7
  • 40
  • 70

1 Answers1

2

You can override SaveChanges on your ObjectContext derived class and modify the last change date just before saving. Something like:

public override int SaveChagnes(SaveOptions saveOptions)
{
    var entities = ObjectStateManager.GetObjectStateEntries(EntityState.Modified)
                                     .Where(e => !e.IsRelationship)
                                     .Select(e => e.Entity)
                                     .OfType<YourEntityType>();

    var currentDate = DateTime.Now;
    foreach(var entity in entities)
    {
        entity.LastChangedDate = currentDate;
    }

    return base.SaveChanges(saveOptions);
}
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670