I am trying to implement a "Save As New" function in a WPF app built on top of Entity Framework. The idea is
- User loads entity A
- User makes changes to entity A
- User clicks "Save As New" which duplicates entity A into A', A' is saved to the database and A is ultimately not touched.
I have been having a lot of trouble getting this to work. Part of the problem is that my entities are somewhat complicated. E.g., I need to support cases of the form MyEntity.Property1.CollectionType<EntityItem>
and such. I don't want to be in the situation of calling Include
on dozens of nested properties. Further, some of the nested entities need to be duplicated, but some are reference data that should not be duplicated. I know exactly which ones these are though.
What I have now looks like the following
// 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();
The problem with the above code is that it duplicates everything, even the properties that have been shallow copied. I understand why this is happening, but I can't figure out the best way to save duplicate some data but not others.
What should I be doing here to get this functionality to work in Entity Framework?