Entity Framework 4.1 DbContext Override SaveChanges Property Not Loading
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 c开发者_如何学GohangeSet = 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();
}
Maybe you are using in a MVC context? If it is, it's maybe just because you don't put your entity properties CreatedOn and ModifiedOn in an hidden field of your page. I got this problem and I solve it with a partial view.
/*My Partial View View/Shared/HiddenSystemValues.cshtml */
@model Models.IAuditable
@Html.HiddenFor(model => model.CreatedOn)
@Html.HiddenFor(model => model.ModifiedOn)
...
/*In All My Pages */
...
@Html.Partial("HiddenSystemValues")
...
精彩评论