Entity Framework 7 SaveChanges

Is there a way to register a callback that will be called before the model in EF7 is stored in the database? What I want to do is set the ModifiedBy and ModifiedDate property that I have on all models. I'm not trying so hard to do this manually before each save, so I'm looking for another general and automatic way.

+4
source share
1 answer

ChangeTracker.Entries()allows you to get all entity changes. You can override SaveChangesin your DbContext and set the changed 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;
        }
    }
}
+7
source

Source: https://habr.com/ru/post/1625539/


All Articles