1

Apologies if I'm missing something obvious! But I'm hoping that Entity Framework has the ability to execute a generic method on all Add/Update actions.

I'm building a custom SaveHistory feature that takes T as a param which essentially would be the Entity Framework object that's being worked on.

Core method:

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

I suppose the questions is, can I centralize the method above to fire on all Add/Update/Remove actions?

If this is not possible, could anyone suggest a better solution?

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
Tez Wingfield
  • 2,129
  • 5
  • 26
  • 46

2 Answers2

2

You can access the entities being saved using the ChangeTracker property of DbContext Override SaveChanges inside your implementation:

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

If you want to validate the entity before saving then you can also access it by overriding ValidateEntity

Community
  • 1
  • 1
Colin
  • 22,328
  • 17
  • 103
  • 197
0

Yes you can, you just have to override default SaveChanges method of entity framework in dbContext class and do what you want to do. whenever you call Context.SaveChanges() your override method will call,

something like this

public override int SaveChanges() {

  // do your changes here
  return base.SaveChanges();
}
Vikas Rana
  • 1,961
  • 2
  • 32
  • 49