How can I automatically set the DateUpdated column using Entity Framework?

I have a bunch of tables with DateUpdated columns.

How can I automatically set these fields to DateTime.Now

when the objects are saved back to the data store when called SaveChanges()

.

I don't need to do it all the way with one code. I would be fine with adding event handlers in all partial classes, but I didn't see anything I could connect. And I would rather keep it in code rather than add triggers to the database.

Here are my ideas:

I think I can do some crazy reflection on the ObjectContext.SavingChanges event, but I don't think this is the best solution.

Or I could add an interface that contains a property DateUpdated

and implement it with all the classes that have this field. Then use the ObjectContext.SavingChanges event to set the property on all changed objects that implement this interface.

Any ideas?

Thanks in advance!

+2


source to share


2 answers


This is one of those extremely rare cases where I think database triggers actually have some usefulness. I usually dislike them a lot ... they have a habit of hiding business logic in the darkest corner of the system. However, for something as simple as the last modified date, I think they might be the simplest, most scalable, and most efficient solution overall.



+3


source


Personally, I would like to create a custom object to inherit my tables. You can set the base type for your tables to this object and then play with it from there. This allows you to override OnPropertyChanged so that it runs whenever any property is changed in the table. This is especially useful if you can rely on convention that the field you are interested in is named "DateUpdated". This will require some minor reflection magic, but not very much.

using System.Reflection;
public class TableBase : System.Data.Objects.DataClasses.EntityObject
{
    protected override void OnPropertyChanged(string property)
    {
        base.OnPropertyChanged(property);

        if (property != "DateUpdated")
        {
            PropertyInfo prop = this.GetType().GetProperty("DateUpdated");
            if (prop != null && prop.PropertyType.IsAssignableFrom(typeof(DateTime)))
            {
                prop.SetValue(this, DateTime.Now, null);
            }
        }
    }
}

      



Set the base type of tables to TableBase and, if they have a "DateUpdated" property, this property will become Datetime.Now as soon as any property is changed.

0


source







All Articles