How do I undo all changes made to a Self-Tracking Entity?

≯℡__Kan透↙ 提交于 2019-12-06 11:41:46

问题


I have a client application that downloads a number of STE's via WCF.

Using a WPF application, users can select an entity from a ListBox, and edit it via a popup UserControl. As the UserControl is bound directly to the object, when a user makes a change it of course affects the object.

I would like to provide a Cancel function which will undo all changes made to the entity.

Any thoughts?


回答1:


You can keep a original copy of the entity. And edit a cloned version of it.
If the user cancels the changes you simply keep using the original copy.




回答2:


I would say as you use WPF just in binded PropertyChanged event save a Dictionary with key PropertyName and value PropertyValue. And after restore the state by using reflection




回答3:


http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/c12bd8c8-231f-4dcc-a665-b048f7debbd7/




回答4:


I'm using this solution so far Extension method

using System.Collections.Generic;
using System.Reflection;

namespace WpfApplication4
{
    public static class EFExtensions
    {
        /// <summary>
        /// Rejects changes made by user
        /// </summary>
        /// <param name="param">Object implementing IObjectWithChangeTracker interface</param>
        public static void RejectChanges(this IObjectWithChangeTracker param)
        {
            OriginalValuesDictionary ovd = param.ChangeTracker.OriginalValues;
            PropertyInfo[] propertyInfos = (param.GetType()).GetProperties();

            foreach (KeyValuePair<string, object> pair in ovd)
            {
                foreach (PropertyInfo property in propertyInfos)
                {
                    if (property.Name == pair.Key && property.CanWrite)
                    {
                        property.SetValue(param, pair.Value, null);
                    }
                }
            }
        }
    }
}

Main code

using System.Linq;

namespace WpfApplication4
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            using (var db = new PlatEntities())
            {
                PacketEPD pd = (from epd in db.PacketEPD
                                select epd).First();
                pd.ChangeTracker.ChangeTrackingEnabled = true;
                pd.EDNo = "1";
                pd.RejectChanges();
            }
        }
    }
}


来源:https://stackoverflow.com/questions/6630566/how-do-i-undo-all-changes-made-to-a-self-tracking-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!