2015-09-24 14 views
1

道歉,如果我失去了一些明显的东西!但我希望实体框架能够在所有添加/更新操作上执行泛型方法。每个实体框架的消防方法添加/更新/删除操作

我正在构建一个自定义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 
    } 
} 

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

如果这是不可能的,任何人都可以提出更好的解决方案吗?

回答

1

您可以访问使用您的实现内部DbContext 覆盖SaveChangesChangeTracker财产被保存的实体:

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

如果要在保存之前验证实体,则还可以通过overriding ValidateEntity

0

是的,你可以,你只需要在dbContext类中重写默认的实体框架SaveChanges方法,并做你想做的事情。只要您拨打Context.SaveChanges()你重写方法将调用,

像这样

public override int SaveChanges() { 

    // do your changes here 
    return base.SaveChanges(); 
} 
+0

似乎似乎......是否有可能接收正在处理的对象?由于SaveChanges通常“提交”而不是“交互” –

+0

@TezWingfield是的,你可以使用ChangeTracker属性 –