From 4b3aab4d56e695ef2b2496460d004ac737043931 Mon Sep 17 00:00:00 2001 From: Lachezar Kuzmanov Date: Thu, 20 Oct 2016 16:21:40 +0300 Subject: [PATCH] This way the inheritors have full control over before and after the call to the SaveChanges of the DbContext happens.I had an issue where i needed to implement audit and i wanted the audit to happen after all the pre save hooks are executed.And there was no way to do it except implementing IDbHookRegistrar myself and coping all the functionality of the DbHookContext. --- src/System.Data.Entity.Hooks/DbHookContext.cs | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/System.Data.Entity.Hooks/DbHookContext.cs b/src/System.Data.Entity.Hooks/DbHookContext.cs index e914bb0..0bb8ebf 100644 --- a/src/System.Data.Entity.Hooks/DbHookContext.cs +++ b/src/System.Data.Entity.Hooks/DbHookContext.cs @@ -128,7 +128,13 @@ public override int SaveChanges() try { - return base.SaveChanges(); + BeforeSaveChanges(); + + var rowsAffected = base.SaveChanges(); + + AfterSaveChanges(rowsAffected); + + return rowsAffected; } finally { @@ -169,6 +175,21 @@ protected void RegisterPostSaveHook(IDbHook dbHook) _postSaveHooks.Add(dbHook); } + /// + /// Called right before SaveChanges method of the DbContext is called, and after pre save hooks are executed. + /// + protected virtual void BeforeSaveChanges() + { + } + + /// + /// Called right after SaveChanges method of the DbContext is called, and before post save hooks are executed. + /// + /// The number of objects written to the underlying database. + protected virtual void AfterSaveChanges(int rowsAffected) + { + } + private void ObjectMaterialized(object sender, ObjectMaterializedEventArgs e) { ObjectStateEntry objectStateEntry;