WPF Cloned/Detached object edit problem - what is the standard?

痴心易碎 提交于 2020-01-01 19:47:07

问题


I am using an ObservableCollection to wrap some of my generated entity framework objects. When the user wants to edit some values , i am opening a popup windows that contains fields, and when the user changes and press save - the changes are saved to the database, and the binded controls are changes as it is an observablecollection.

To prevent the user from working on the same binded object (it causes the visual change of every binded control on the same time) i want to use some functionality the clone the object, and then detach the original, attach the cloned object, and save it to the database. The problem is that the cloned object does not save properly to the database. If i try only to detach the object, edit and then attach - when detached it loses all its parent and child refernces...

What is the CRUD standard in WPF? How can i cleanly edit a current row, while keeping it in an ObservableCollection?

Please Help....

Oran


回答1:


Well it seems that i have found a fine solution.

  1. First implement your cloneable object container :

    public class ClonableObjectContainer : Object , ICloneable
    {
        private Object data;
    
        public ClonableObjectContainer(Object obj)
        {
            data = obj;
        }
    
        public Object Data
        {
            get { return data; }
        }
    
        public object Clone()
        {
            return (ClonableObjectContainer)this.MemberwiseClone();
        }
    }
    
  2. Then use this object with its Clone method to create your detached edit object:

             ClonableObjectContainer coc = new ClonableObjectContainer(actor);
             EntityObject editEntity = (EntityObject)coc.Data;
    
  3. After performing changes, detach the original object from the ObjectContext , attach the cloned object, change its state to EntityState.Modified and gracefully save:

            ContextManager.CurrentObjectContext.Detach(oldItem);
            ContextManager.CurrentObjectContext.Attach((IEntityWithKey)item);
            ContextManager.CurrentObjectContext.ObjectStateManager.ChangeObjectState(item, EntityState.Modified); 
            ContextManager.Save();
    

Hope it helps... Oran

EDIT : If the followings does not work for you, please check the continued discussion : Entity Framework Attach Exception After Clone



来源:https://stackoverflow.com/questions/3865738/wpf-cloned-detached-object-edit-problem-what-is-the-standard

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