Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 4th, 2012  |  syntax: None  |  size: 1.20 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to deep copy an entity
  2. public static T DeepClone<T>(this T obj)
  3.     {
  4.         using (var ms = new MemoryStream()) {
  5.             var bf = new BinaryFormatter();
  6.             bf.Serialize(ms, obj);
  7.             ms.Position = 0;
  8.             return (T)bf.Deserialize(ms);
  9.         }
  10.     }
  11.        
  12. db.Detach(myEntity);
  13. myEntity.EntityKEy = null;
  14. Entity newEntity = new Entity();
  15. newEntity = DeepClone<Entity>(Entity);
  16. db.Entities.AddObject(newEntity);
  17. db.SaveChanges();
  18.        
  19. Entity newEntity = new Entity();
  20. Eneity Entity = db.Include("ChildEntity").Where(p=>p.Id==Id).Single();
  21. newEntity = DeepClone<Entity>(Entity);
  22. db.Detach(myEntity);
  23. myEntity.EntityKEy = null;
  24. db.Entities.AddObject(newEntity);
  25. db.SaveChanges();
  26.        
  27. var entity = db.Entities.Include("ChildEntity.ChildChildEntity")
  28.         .Where(l=>l.ID == myId).Single();
  29.        
  30. Entity oldEntity = db.Include("ChildEntity").Where(p => p.Id == Id).Single();
  31. Entity newEntity = oldEntity.DeepClone(); // assuming you've put your DeepClone extension method in a static class so that it can be used as an extension
  32. newEntity.EntityKey = null;
  33. foreach(var childEntity in newEntity.ChildEntities)
  34. {
  35.     childEntity.EntityKey = null;
  36. }
  37. db.Entities.AddObject(newEntity);
  38. db.SaveChanges();