2

I have 2 class in c# :

 public class Item
 { 
   public int Id { get; set; }
   public string Name { get; set; }

   public List<SubItem> SubItems { get; set; }

   public Item DeepClone()
   {
     Item item = this.MemberwiseClone();
     item.SubItems = this.SubItems.Select(i => i.DeepClone()).ToList();
     return item;
   }
 }

 public class SubItem
 { 
   public int Id { get; set; }
   public string Name { get; set; }

   public SubItem DeepClone()
   {
     SubItem subItem = this.MemberwiseClone();
     return subItem;
   }
 }

When i call DeepClone function on Item class object, it clones all the members except SubItems list. When i access the subItems list through cloned object it threws an exception

The entity wrapper stored in the proxy does not reference the same proxy.

What i am doing wrong here ??

Jehof
  • 34,674
  • 10
  • 123
  • 155
user1740381
  • 2,121
  • 8
  • 37
  • 61
  • Don't use the shallow MemberwiseClone() when you want a deep clone. Try Item item = new Item() { Id = this.Id, Name = this.Name }; – Hans Passant Apr 10 '14 at 06:56
  • If you contain those items in a `List` for example you can even do `yourItemList.ToList()`, it will generate a new list from your objects. – Tolga Evcimen Apr 10 '14 at 07:11

0 Answers0