Problem

DataSets offer a method “GetChanges()” to check if the user modified any data, so the application can ask the user if the changes should be saved, e.g. when closing the window. But there is no “ready-to-use” method for this when using Entity Framework.

Solution

dbEntities db = new dbEntities();
//...
//Place the following code e.g. in Window_Unloaded() Event (WPF) or FormClosing() in (WinForms)
bool changesMade = db.yourtable.Context.
                   ObjectStateManager.
                   GetObjectStateEntries(EntityState.Added |
                                         EntityState.Deleted |
                                         EntityState.Modified
                                        ).Any();

Source

Extension Method

As an alternative, you can use the following code to create an extension method:

/// <returns>True, if any row of the table changed</returns>
        public static bool HasUnsavedChanges<T>(this ObjectSet<T> table)
            where T : class
        {
            return table.Context.
                    ObjectStateManager.
                    GetObjectStateEntries(EntityState.Added |
                                            EntityState.Deleted |
                                            EntityState.Modified
                                            ).Any();
        }

So you can call e.g. “db.yourtable.HasUnsavedChanges()”.

 

Extension Method for whole Context

/// <summary>
        /// Checks whole EF context if there are objects to be saved, asks user, then saves to DB
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static MessageBoxResult SaveChangesAfterAskingUser(this ObjectContext context)
        {
            bool changes = 
            context.ObjectStateManager.GetObjectStateEntries(EntityState.Added |
                                            EntityState.Deleted |
                                            EntityState.Modified
                                            ).Any();
                    
            if (!changes)
                return MessageBoxResult.None;

            MessageBoxResult result = MessageBox.Show("Save changes?", "Save changes", MessageBoxButton.YesNoCancel);
            if (result == MessageBoxResult.Yes)
            {
                context.SaveChanges();
            }
            return result;
            
        }

Using this method, call e.g. “db.SaveChangesAfterAskingUser()”.

Share This:

  [email protected]