2

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?

1 Answer 1

3

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.