Is there a way to run code when an entity is updated? For example I have an entity that is updated many places in my code. I want to be able to update a DateTimeUpdated field any time that entity is updated without changing every function that updates that entity.
CodePudding user response:
This is typically done by overriding the SaveChanges
method in the DbContext.
Start by introducing a base class or a common interface for your editable entities that you want to track the DateTimeUpdated for:
public abstract class EditableEntityBase
{
public DateTime DateTimeUpdated { get; internal set; }
}
Your entities that you want to track this for should extend this class or implement a contract interface that will expose the property.
Then in your DbContext, override the SaveChanges
method and insert:
var updatedEntities = ChangeTracker.Entries()
.Where(x => x.State == EntityState.Modified)
.Select(x => x.Entity)
.OfType<EditableEntityBase>();
foreach (var entity in updatedEntities)
{
entity.DateTimeUpdated = DateTime.Now; // or DateTime.UtcNow
}
return base.SaveChanges();
You can also include x.State == EntityState.Added
for new records, though generally I'd rely on a Default at the DB to capture it on insert.