Entity Framework 7 SaveChanges

寵の児 提交于 2021-02-07 06:57:21

问题


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.


回答1:


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;
        }
    }
}


来源:https://stackoverflow.com/questions/34951613/entity-framework-7-savechanges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!