I used the code from the Override Save Changes question to implement auditing in my application. When an entity is added everything is great. However, when an entity is modified the "CreatedOn" date is never loaded.
It is always null, so the initial "CreatedOn" date gets removed from the database.
I also tried looking in the OriginalValues collection stored in the entity, and it is populated for the "ModifiedOn" date but not for the "CreatedOn" date. Both fields are populated in the database...why would one be loaded by EF and one not be loaded?
public override int SaveChanges()
{
var changeSet = ChangeTracker.Entries<IAuditable>();
if (changeSet != null)
{
foreach (DbEntityEntry<IAuditable> entry in changeSet)
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedOn = DateTime.Now;
entry.Entity.ModifiedOn = DateTime.Now;
break;
case EntityState.Modified:
entry.Entity.ModifiedOn = DateTime.Now;
//entry.Entity.CreatedOn date always null here
break;
}
}
}
return base.SaveChanges();
}