views:

286

answers:

2

I have a bunch of tables that have DateUpdated columns.

How can I have those fields automatically set to DateTime.Now when the objects are persisted back to the data store when SaveChanges() is called.

I don't need to do it across the board with one piece of code. I would be OK with adding event handlers in all of the partial classes, but I didn't see anything I could hook into. And I'd rather keep it in the code, rather than adding triggers to the database.

Here are my ideas:

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

Or, I could add an interface that contains a DateUpdated property, and implement it with all the classes that have that field. Then use ObjectContext.SavingChanges event to set the property on all of the changed objects that implement that interface.

Any ideas?

Thanks in advance!

A: 

Personally, I'd go with creating a custom object for my tables to inherit from. 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 will execute whenever any property is changed on the table. This is particularly useful if you can count on the convention that the field you're interested in is named "DateUpdated". It'd take some minor reflection magic, but not really 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 your tables to TableBase and if they have a property of "DateUpdated" that property will become Datetime.Now as soon as any property is changed.

Jacob Proffitt
Unfortunately, I think the "OnPropertyChanged" event fires every time the entity is changed, even when data is being loaded. So I think doing a select would cause the field to be updated in this case.
SkippyFire
That's okay. Further experimentation reveals that Base Type is hard-wired to be table entities within the same model rendering it useless for this purpose. So much easier in Linq for SQL. <sigh>
Jacob Proffitt
+2  A: 

This is one of those exceedingly rare cases where I think database triggers actually have some utility. Normally I dislike them strongly... they have a habit of hiding business logic in the darkest corner of a system. However, for something as simple as a Last Modified Date, I think they may be the simplest, most scalable, and best performing solution overall.

Dave Swersky