Inspecting Database Changes in Entity Framework

Tags: .NET, entity framework

Author: Ryan Olshan

In the event that you need to perform additional manipulation on data with Entity Framework upon save, the SaveChanges method needs to be overridden.  The easiest way to go about this is to create a partial class of your ObjectContext class.

In the changedEntries collection below, each ObjectStateEntry in the collection contains an Entity property, which gives you access to the entity being added, deleted or modified for further inspection.


using System.Collections.Generic;

using System.Data;

using System.Data.Entity.Infrastructure;

using System.Data.Objects;

public partial class DatabaseContext


   public override int SaveChanges(SaveOptions options)


      IEnumerable<ObjectStateEntry> changedEntries = ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified);

      //Code here for manipulation before save

      int numberOfChanges = base.SaveChanges(options);

      //Code here for manipulation after save

      return numberOfChanges;




Imports System.Collections.Generic

Imports System.Data

Imports System.Data.Entity.Infrastructure

Imports System.Data.Objects

Public Partial Class DatabaseContext

   Public Overrides Function SaveChanges(options As SaveOptions) As Integer

      Dim changedEntries As IEnumerable(Of ObjectStateEntry) = ObjectStateManager.GetObjectStateEntries(EntityState.Added Or EntityState.Deleted Or EntityState.Modified)

      'Code here for manipulation before save

      Dim numberOfChanges As Integer = MyBase.SaveChanges(options)

      'Code here for manipulation after save

      Return numberOfChanges

   End Function

End Class

© 2020 RK Consulting. All rights reserved.