Setting the update timestamp in Entity Framework

entity-framework

Question

All of our database tables have UpdateUserID and UpdateTS. I'd like to have this set if my entity has changes. Is there a way I can have this update on the spot conditionally?

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

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

Accepted Answer

You should be able to handle the SavingChanges event (example here) and perform logic as outlined by @sander

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

Popular Answer

Here's an implementation of the other two ideas, with the following considerations

  • Ensure that you either create proxies that automatically detect changes, or that you have manually detected changes, prior to the call to SaveChanges(). If not, the object state will be EntityState.Unmodified, and the last modified timestamp will not be updated.
  • I have expanded the code to also set the last modified timestamp when the object is first created (EntityState.Added)

The Code

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