EF Core: Built in Created and Edited timestamps

asp.net-core entity-framework entity-framework-core

Question

The title is quite self-explanatory. Is there a built-in mechanism to support Created and Edited timestamps on records in a code-first database in Entity Framework Core?

Something like :created_at and :updated_at in Ruby on Rails migrations. I could not find any documentation concerning this. If no out-of-the-box mechanism is present, is there a best practice how to implement those columns?

1
8
10/25/2017 8:27:45 AM

Popular Answer

The non EF Core solutions don't apply to EF Core without some amount of rework. I wanted to allow certain entities to have CreatedAt and LastModified timestamps that updated in a reasonably automated way. This is what I ended up doing.

  1. Defined an interface - ITimeStampedModel that my models could inherit from that required them to have the timestamps I wanted:

    public interface ITimeStampedModel
    {
        DateTime CreatedAt {get; set;}
        DateTime LastModified {get; set;}
    }
    
  2. Override SaveChanges on my DbContext to look for new or modified models, and update their timestamps appropriately:

    public override int SaveChanges()
    {
        var newEntities = this.ChangeTracker.Entries()
            .Where(
                x => x.State == EntityState.Added &&
                x.Entity != null &&
                x.Entity as ITimeStampedModel != null
                )
            .Select(x => x.Entity as ITimeStampedModel);
    
        var modifiedEntities = this.ChangeTracker.Entries() 
            .Where(
                x => x.State == EntityState.Modified &&
                x.Entity != null &&
                x.Entity as ITimeStampedModel != null
                )
            .Select(x => x.Entity as ITimeStampedModel);
    
        foreach (var newEntity in newEntities)
        {
            newEntity.CreatedAt = DateTime.UtcNow;
            newEntity.LastModified = DateTime.UtcNow;
        }
    
        foreach (var modifiedEntity in modifiedEntities)
        {
            modifiedEntity.LastModified = DateTime.UtcNow;
        }
    
        return base.SaveChanges();
    }
    

Anyone have a better solution?

4
9/8/2019 2:14:57 PM


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