I implemented similar solution on how we can modify created and updated date upon saving data through EF Core as what is suggested here Populate Created and LastModified automagically in EF Core.
void OnEntityStateChanged(object sender, EntityStateChangedEventArgs e)
{
if (e.NewState == EntityState.Modified && e.Entry.Entity is IHasCreationLastModified entity)
entity.LastModified = DateTime.Now;
}
At first I thought this will be triggered only when SaveChanges()
is called. But apparently it is also called on Entry()
// Get entity
var student = _dbContext.Students.Find(studentId);
// Modify student object
student.Name = "New student name";
// Called Entry(), trigger ChangeTracker.StateChanged
var entry = _dbContext.Entry(student);
// Doesn't trigger ChangeTracker.StateChanged
_dbContext.SaveChanges();
I found that ChangeTracker.StateChanged
is triggered when _dbContext.Entry(student)
is called. Then it doesn't get triggered again when _dbContext.SaveChanges()
is called. And it also passes the condition above if (e.NewState == EntityState.Modified && e.Entry.Entity is IHasCreationLastModified entity)
.
My assumption why it is not triggered again when SaveChanges()
is called, because there is no new update to the entity after Entity()
is called.
This results in the LastModified
property being assigned when .Entry(student)
is called, instead of when .SaveChanges()
is called.
Is there a way to only update LastModified
property once when SaveChanges
is called on the scenario above?