Search code examples
c#wpflinqdatacontextinotifypropertychanged

WPF Update UI after Revert Changes From LINQ to SQL


I read this question but unfortunately not found any solution to update ui after reverting changes.

How can I reject all changes in a Linq to SQL's DataContext?

All of my properties are derived from INotifyPropertyChanged.

var changeSet = dataContext.GetChangeSet();
if (changeSet != null)
{
    var updates = changeSet.Updates.ToArray();
    dataContext.Refresh(RefreshMode.OverwriteCurrentValues, changeSet.Updates);

    foreach (var o in updates)
    {
        INotifyPropertyChanged entity = (INotifyPropertyChanged)o;
        // What i have to do to force them trigger PropertyChanged event ???
    }
}

Solution

  • First I add a Method to all of my Linq2SQL classes:

    public partial class Setting
    {
        public void SendPropertyChangedFromOutside(string propName)
        {
            SendPropertyChanged(propName);
        }
    }
    
    public partial class User
    {
        public void SendPropertyChangedFromOutside(string propName)
        {
            SendPropertyChanged(propName);
        }
    }
    

    then call UndoDBChanges method:

    public static void UndoDBChanges(System.Data.Linq.DataContext dataContext) {
    var changeSet = dataContext.GetChangeSet();
    if (changeSet != null)
    {
        var updates = changeSet.Updates.ToArray();
        dataContext.Refresh(RefreshMode.OverwriteCurrentValues, changeSet.Updates);
    
        foreach (var o in updates)
        {
            try
            {
                Type t = o.GetType();
                dynamic obj = Convert.ChangeType(o, t);
    
                foreach (System.Reflection.PropertyInfo prop in t.GetProperties())
                {
                    obj.SendPropertyChangedFromOutside(prop.Name);
                }
            }
            catch
            { }
        }
    }}