【问题标题】:Fire method on every Entity Framework Add/Update/Remove action每个实体框架添加/更新/删除操作的触发方法
【发布时间】:2015-09-24 07:54:09
【问题描述】:

抱歉,如果我遗漏了一些明显的东西!但我希望实体框架能够对所有添加/更新操作执行通用方法。

我正在构建一个自定义 SaveHistory 功能,该功能将 T 作为参数,本质上是正在处理的实体框架对象。

核心方法:

//TODO - Requires additional logic
public void SaveHistory<T>(T type, [CallerFilePath]string callerFilePath = "")
{
    //Caller File Path just returns the location of where the method was executed
    //This enables us to retrieve the module location

    //Get the Name of the class(Type that's been passed in)
    var className = typeof(T).Name;

    //Get a collection of module names
    var enumNames = Enum.GetNames(typeof (Department));

    //Does any of the module names equal the executing assembly
    if (enumNames.Any(callerFilePath.Contains))
    {
        //Now I can search the string to see if an action came from a module
    }
    else
    {
        //If not it could be an error or calling from a core object
        //Needs work
    }
}

我想问题是,我可以集中上述方法来触发所有添加/更新/删除操作吗?

如果这不可能,谁能提出更好的解决方案?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您可以使用DbContextChangeTracker 属性访问正在保存的实体 在你的实现中覆盖SaveChanges

    public override int SaveChanges()
    {
       foreach (var e in ChangeTracker.Entries())
       {
           SaveHistory(e.Entity);
       }
       return base.SaveChanges();
    }
    

    如果您想在保存之前验证实体,也可以通过overriding ValidateEntity 访问它

    【讨论】:

      【解决方案2】:

      是的,你可以,你只需要在 dbContext 类中覆盖实体框架的默认 SaveChanges 方法,然后做你想做的事。每当您调用Context.SaveChanges() 时,您的覆盖方法都会调用,

      类似的东西

      public override int SaveChanges() {
      
        // do your changes here
        return base.SaveChanges();
      }
      

      【讨论】:

      • 似乎有道理...是否可以接收正在处理的对象?由于 SaveChanges 通常是“提交”而不是“交互”
      • @TezWingfield 是的,您可以为此使用 ChangeTracker 属性
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      相关资源
      最近更新 更多