Is there any way to register a callback that will be called before a model in EF7 is saved to the database? What I want to do is to set a ModifiedBy and ModifiedDate property that I have on all models. I'm not that keen to do this manually before each save so I'm looking for some more generic and automatic way.
-
Have you seen Generated properties?– Rowland ShawJan 22, 2016 at 16:38
-
From what I understand Generated Properties are used to mark that the property can be set by the database. I want to set the property in my c# code in a generic way that ensures that it happens on every save.– AbrisJan 22, 2016 at 17:43
Add a comment
|
1 Answer
ChangeTracker.Entries()
allows you to get all of the entity changes. You could override SaveChanges
in your DbContext and set the modified properties using something like the following code.
public override int SaveChanges()
{
SetModifiedInformation();
return base.SaveChanges();
}
public override async Task<int> SaveChangesAsync( CancellationToken cancellationToken = new CancellationToken() )
{
SetModifiedInformation();
return await base.SaveChangesAsync( cancellationToken );
}
private void SetModifiedInformation()
{
foreach (var entityEntry in ChangeTracker.Entries())
{
var entity = entityEntry.Entity as ChangeTracking;
if (entity != null)
{
entity.ModifiedBy = "Get User Here";
entity.ModifiedTime = DateTime.Now;
}
}
}
-
Should one check for entityEntry.State != EntityState.Unchanged && entityEntry.State != EntityState.Detached aswell?– AbrisJan 23, 2016 at 14:12
-
Yes that would be good to make sure that entities are not marked as modified when they shouldn't be Jan 23, 2016 at 14:15