public partial class MyEntityContext
{
partial void OnContextCreated()
{
SavingChanges += OnSavingChanges;
}
private void OnSavingChanges(object sender, EventArgs e)
{
var now = DateTime.Now;
foreach (var entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
{
if (!entry.IsRelationship)
{
var timestampedEntity = entry.Entity as ITimestampedEntity;
if (timestampedEntity != null)
{
timestampedEntity.DateModified = now;
var entity = entry.Entity as EntityObject;
if (entity != null && entity.EntityState == EntityState.Added)
{
timestampedEntity.DateCreated = now;
}
}
}
}
}
}
internal interface ITimestampedEntity
{
DateTime DateCreated { get; set; }
DateTime DateModified { get; set; }
}
Now for every entity that implements the ITimestampedEntity interface, the DateCreated and DateModified fields will automagically be set/updated.
The above code is covered under the Logos Code Blog License.
No comments:
Post a Comment