Setting the update timestamp in Entity Framework

entity-framework

Question

UpdateUserID and UpdateTS are available in all of our database tables. If my entity changes, I'd want to have this set. Is there a way I can get this update immediately with a condition?

If I explicitly set UpdateTS in the code, it will always update the object and report that my entity has changed.

1
10
10/28/2012 10:05:13 PM

Accepted Answer

You ought to be able to manage the SavingChanges event (instance here) and use the @sander's suggested logic.

3
1/20/2010 1:46:15 AM

Popular Answer

Here is how the other two concepts are put into practice, with the following things to keep in mind:

  • Prior to calling SaveChanges, be careful to either setup proxies that automatically detect changes or manually detect changes (). Otherwise, the object state will beEntityState.Unmodified , and no change will be made to the latest changed timestamp.
  • When the object is first created, I've changed the code to include set the latest modified timestamp (EntityState.Added )

The Law

public interface IHasLastModified
{
    DateTime? LastModified { get; set; }
}

public class MyClass : IHasLastModified
{
    public virtual int Id { get; set; }

    public virtual string SomeOtherProperty { get; set; }

    public virtual DateTime? LastModified { get; set; }
}

public class MyContext : DbContext
{
    public override int SaveChanges()
    {            
        DateTime now = DateTime.UtcNow;
        foreach (ObjectStateEntry entry in (this as IObjectContextAdapter).ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
        {
            if (!entry.IsRelationship)
            {
                IHasLastModified lastModified = entry.Entity as IHasLastModified;
                if (lastModified != null)
                    lastModified.LastModified = now;
            }
        }

        return base.SaveChanges();
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow