Ahmed Mujtaba
Ahmed Mujtaba

Reputation: 2248

Update Created and Modified Date fields in DBContext class with Entity framework

Is there a way I can update or insert entities with their DateCreated and UpdateDate fields set to some date when the entity is being saved.

I have a Data Provider helper class that encapsulated update, add and delete functions for all my data objects. However when the object is being saved, DateCreated and UpdateDate fields are null and I'm not assigning them the current date. I wanna be able to save my objects with those dates assigned. I wanna avoid changing the code everywhere where the save action is performed. Is it possible to do it in the DBContext class?

Upvotes: 2

Views: 1378

Answers (1)

Ilya Chumakov
Ilya Chumakov

Reputation: 25039

Override DbContext.SaveChanges to implement this cross-cut feature. If you need to assign properties only to certain entity types, then an interface or class attribute can be used to distinguish them instead of slow Reflection check:

public partial class PostalDbContext
{
    public override int SaveChanges()
    {
        DateTime time = DateTime.Now;

        var entries = ChangeTracker.Entries()
            .Where(entry => entry.Entity is ITrackableEntity)
            .ToList();

        ITrackableEntity x;

        foreach (var entry in entries.Where(e => e.State == EntityState.Added))
        {
            entry.SetPropertyValue(nameof(x.DateCreated), time);
        }

        foreach (var entry in entries.Where(e => e.State == EntityState.Modified))
        {
            entry.SetPropertyValue(nameof(x.DateModified), time);
        }

        return base.SaveChanges();
    }
}

public static class DbEntityEntryEx
{
    public static void SetPropertyValue<T>(this DbEntityEntry entry, string propertyName, T time)
    {
        entry.Property(propertyName).CurrentValue = time;
    }
}

Upvotes: 3

Related Questions