I am evaluating Entity Framework 4.0 and I am wondering how I can get access to entities just before they开发者_Go百科 are saved to set DateCreated.
With NHibernate this could be done using a listener, if that helps?
You could use the ObjectContext
event SavingChanges
, retrieve the entities that have an the state EntityState.Added
, and set the DateCreated for those objects. You might need a helper interface to facilitate a more agnostic handler and avoid the use of reflection. You might also be able to use dynamic, although you would run the chance of runtime exceptions being thrown, which would hurt performance:
private void context_SavingChanges(object sender, EventArgs e)
{
ObjectContext context = sender as ObjectContext;
if (context != null)
{
foreach (ObjectStateEntry entry in context.ObjectStateManager.GetObjectStateEntries (EntityState.Added)
{
IEntityWithTimestamps entity = entry.Entity as IEntityWithTimestamps;
if (entity != null)
{
entity.DateCreated = DateTime.Now;
}
}
}
}
精彩评论