0

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?

Kris Harper
  • 5,672
  • 8
  • 51
  • 96
  • Is your method shallow copying the original's `Id`? – jamesSampica May 03 '16 at 14:51
  • @Shoe In the `Clone` method anything that I want inserted as a new entity I set the `Id` property to 0. That's the easiest way I've found to get EF to treat that entity as new. Everything that I want not duplicated gets the same `Id`. – Kris Harper May 03 '16 at 15:33
  • Try opening your context before cloning. You also shouldn't need to find the original if your intent is to save a new entity. – jamesSampica May 03 '16 at 18:12
  • @Shoe When you say opening context before cloning, do you mean move the `Context = new MyEntityContext();` line above the `Clone()` line? – Kris Harper May 03 '16 at 21:27

0 Answers0