views:

100

answers:

2

Based on this link it looks like I can get date inserted / date modified information "for free" (without the need for triggers etc.) using Sql Server 2008 by simply enabling Change Tracking. I am using Entity Framework to access the data. My question is, how do I access date modified / date inserted information for the database records via Entity Framework and LINQ?
I'm using VS2008 so I don't have the new EF v4 stuff yet (but if it can be done in the new EF please let me know).
Thanks.

A: 

Aw, nevermind. I found it plenty easy to just create the Inserted and LastModified columns in each table myself, set a default value for each, and build an update trigger for LastModified. That seems to be what people do, and the Change Tracking looks like it's mainly set up for sync'ing. Right?

Vince
WOAH!!! But now although the default and the trigger work great if I insert/edit by hand in the database, they stay null when added/modified using Entity Framework! I even tried [Bind(Exclude = "Id, Created, LastModified")] but still no luck. Help! Can I "un-accept" my prior answer :-)
Vince
A: 

OK, this works beautifully (also see this article)...

public partial class MyEntities
{
    partial void OnContextCreated()
    {
        this.SavingChanges += new System.EventHandler(CustomSavingChangesLogic);
    }

    /// <summary>
    /// Apply timestamps
    /// </summary>
    public void CustomSavingChangesLogic(object sender, System.EventArgs e)
    {
        var changedEntities = ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified);
        foreach (var stateEntryEntity in changedEntities)
        {
            if(!stateEntryEntity.IsRelationship) {
                var entity = stateEntryEntity.Entity;
                var lastModifiedPropInfo = entity.GetType().GetProperty("LastModified");
                if (lastModifiedPropInfo != null)
                    lastModifiedPropInfo.SetValue(entity, DateTime.UtcNow, null);
                if (stateEntryEntity.State == EntityState.Added)
                {
                    var createdPropInfo = entity.GetType().GetProperty("Created");
                    if (createdPropInfo != null)
                        createdPropInfo.SetValue(entity, DateTime.UtcNow, null);
                }

            }
        }
    } 

}
Vince