我正在尝试实施一个"另存为新"功能在构建于Entity Framework之上的WPF应用程序中。这个想法是
我一直在努力解决这个问题。部分问题是我的实体有点复杂。例如,我需要支持MyEntity.Property1.CollectionType<EntityItem>
等形式的案例。我不想在几十个嵌套属性上调用Include
。此外,一些嵌套实体需要复制,但有些是不应重复的参考数据。我确切地知道这些是哪些。
我现在的内容如下所示
// Entity is a reference to the entity currently being edited
// Clone is a call to a copy constructor that does the appropriate deep and shallow copies. I.e., entities that need to be duplicated are deep copied and reference data entities are shallow copied.
MyEntity clone = Entity.Clone();
// Reload the current instrument from the database by resetting the context and finding the Entity again.
// This is needed so that when we call SaveChanges, the original entity isn't updated.
Context = new MyEntityContext();
Entity = Context.MyEntities.Find(Entity.Id);
// I have also tried Context.Entry(Entity).Reload(), but this does not reload all the navigation properties (e.g., Entity.Property1.AnotherProperty is not reloaded).
Context.MyEntities.Add(clone);
Context.SaveChanges();
上面代码的问题在于它复制了所有内容,甚至是已经浅层复制的属性。我理解为什么会这样,但我无法找出保存重复某些数据的最佳方法,而不是其他数据。
我应该在这做什么才能让这个功能在Entity Framework中运行?