Populate Created and LastModified automagically in EF Core

前端 未结 2 636
再見小時候
再見小時候 2020-12-09 22:53

Looking forward to build a framework, (No repository pattern to working with DbSets directly) to autopopulate Created and last modified automatically, rather than spitting o

2条回答
  •  青春惊慌失措
    2020-12-09 23:27

    One possible solution (the one we're currently using where I work) is to override the SaveChanges() method in the DbContext and add a little bit of code to loop through changed entities setting the values

    public override int SaveChanges()
    {
        var changedEntriesCopy = ChangeTracker.Entries()
                    .Where(e => e.State == EntityState.Added ||
                    e.State == EntityState.Modified ||
                    e.State == EntityState.Deleted)
                    .ToList();
        var saveTime = DateTime.Now;
    
            foreach (var entityEntry in changedEntriesCopy)
            {
                if (entityEntry.Metadata.FindProperty("Created") != null && entityEntry.Property("Created").CurrentValue == null)
                {
                    entityEntry.Property("Created").CurrentValue = saveTime;
                }
    
                if (entityEntry.Metadata.FindProperty("Updated") != null)
                {
                    entityEntry.Property("Updated").CurrentValue = saveTime;
                }
            }
        return base.SaveChanges();
    }
    

    Our situation is basically set up similar to that - Created in our situation is nullable so that when a new entity is created the value is null in code up to creation (makes it easy to check if Created has been populated ever).

    There may be other solutions, but this was the easiest to get set up for us, and hasnt had any noticeable performance impact

提交回复
热议问题