Below I have created a demo entity to demonstrate what I\'m looking for:
public class User : IValidatableObject
{
public string Name { get; set; }
I have an almost identical situation and I manage it by handling the SavingChanges event on the context.
First I create an interface that defines the timestamping operations:
public interface IHasTimeStamp
{
void DoTimeStamp();
}
Then I implement this interface in my entities:
Public class User : IHasTimeStamp
(
public void DoTimeStamp()
{
if(dataContext.Entry<User>(this).State == System.Data.EntityState.Added)
{
//add creation date_time
this.CreationDate=DateTime.Now;
}
if(dataContext.Entry<User>(this).State == System.Data.EntityState.Modified)
{
//update Updation time
this.UpdatedOnDate=DateTime.Now;
}
}
}
The final step is to register the SavingChanges handler and implement it.
public partial class MyEntities
{
partial void OnContextCreated()
{
// Register the handler for the SavingChanges event.
this.SavingChanges
+= new EventHandler(context_SavingChanges);
}
// SavingChanges event handler.
private static void context_SavingChanges(object sender, EventArgs e)
{
// Validate the state of each entity in the context
// before SaveChanges can succeed.
foreach (ObjectStateEntry entry in
((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
{
if (!entry.IsRelationship && (entry.Entity is IHasTimeStamp))
{
(entry.Entity as IHasTimeStamp).DoTimeStamp();
}
}
}
}