实体框架7保存更改 [英] Entity Framework 7 SaveChanges

查看:59
本文介绍了实体框架7保存更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将EF7中的模型保存到数据库之前,是否有任何方法可以注册将要调用的回调?我想要做的是设置所有模型上都有的ModifiedBy和ModifiedDate属性.我不太想在每次保存之前手动执行此操作,因此我正在寻找一些更通用和自动的方法.

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.

推荐答案

ChangeTracker.Entries()允许您获取所有实体更改.您可以在DbContext中覆盖 SaveChanges 并使用类似以下代码的方式设置修改后的属性.

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

这篇关于实体框架7保存更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆