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.
You should be able to handle the SavingChanges event (example here) and perform logic as outlined by @sander
Here's an implementation of the other two ideas, with the following considerations
EntityState.Unmodified
, and the last modified timestamp will not be updated.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();
}