I have the following overide in my ApplicationDBContext so that whnenever a new entity is added or modified it adds a created or modifed timestamp. It works for when I create an entity but seems to fail when I do an update - the modifed datestamp doesnt seem to update?
public override int SaveChanges()
{
var modifiedEntries = ChangeTracker.Entries()
.Where(x => x.Entity is AuditableEntity
&& (x.State == EntityState.Added || x.State == EntityState.Modified));
foreach (var entry in modifiedEntries)
{
AuditableEntity entity = entry.Entity as AuditableEntity;
if (entity != null)
{
string userId = System.Threading.Thread.CurrentPrincipal.Identity.GetUserId();
DateTime now = DateTime.UtcNow;
if (entry.State == EntityState.Added)
{
entity.CreatedBy = userId;
entity.CreatedDate = now;
}
else
{
base.Entry(entity).Property(x => x.CreatedBy).IsModified = false;
base.Entry(entity).Property(x => x.CreatedDate).IsModified = false;
}
entity.ModifiedBy = userId;
entity.ModifiedDate = now;
}
}
return base.SaveChanges();
}
This is my controller action to update the model:
var post = _postRepository.GetPost(viewModel.Id);
UpdateModel(post, "", includeProperties: new[] { "Subject", "TypeId", "CategoryId" });
_unitOfWork.Complete();
_unitOfWork.Complete() simply calls the following:
public void Complete()
{
_context.SaveChanges();
}
The Auditable class is an abstract class whith the Post inherits from:
public abstract class AuditableEntity
{
[ScaffoldColumn(false)]
public DateTime CreatedDate { get; set; }
[MaxLength(128)]
[ScaffoldColumn(false)]
public string CreatedBy { get; set; }
[ScaffoldColumn(false)]
public DateTime ModifiedDate { get; set; }
[MaxLength(128)]
[ScaffoldColumn(false)]
public string ModifiedBy { get; set; }
public ApplicationUser Creator { get; set; }
public ApplicationUser Modifier { get; set; }
}
public class Post : AuditableEntity
{
...
}
All the fields get updated apart from the modifiedby and modifieddate?
My understanding was that when you call UpdateModel, Entity Framework's automatic change tracking sets the Modified flag on the entity?