title: Recursive Entity Update
body: <p>I have an entity which holds a list of entities (same as root entity) to represent a Folder structure:</p>
  
  <pre><code>public class SopFolder
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public DateTime? LastUpdated { get; set; }
      public int Status { get; set; }
      public virtual ICollection&lt;SopField&gt; SopFields { get; set; }
      public virtual ICollection&lt;SopFolder&gt; SopFolderChildrens { get; set; }
      public virtual ICollection&lt;SopBlock&gt; Blocks { get; set; }
      public virtual ICollection&lt;SopReview&gt; Reviews { get; set; }
  }
  </code></pre>
  
  <p>This entity is stored in my DB using Code-First Approach which is working fine. I then print the entity to a KendoUI Treeview, let the user modify it and on "save" post it back to the Server to an Action as <code>IEnumerable&lt;TreeViewItemModel&gt; items</code>.</p>
  
  <p>I then look for the ROOT entity with all it's children (there is only one root) and convert it back into an SopFolder object.</p>
  
  <p>To get the full object updated in the database I do the following:</p>
  
  <pre><code> List&lt;SopFolder&gt; sopfolderlist = ConvertTree(items.First());
  
          SopFolder sopfolder = sopfolderlist[0];
  
          if (ModelState.IsValid)
          {
              SopFolder startFolder = new SopFolder { Id = sopfolder.Id };
  
              //db.SopFolders.Attach(startFolder);
             // db.SopFolders.Attach(sopfolder);
  
              startFolder.Name = sopfolder.Name;
              startFolder.LastUpdated = sopfolder.LastUpdated;
              startFolder.SopFields = sopfolder.SopFields;
              startFolder.SopFolderChildrens = sopfolder.SopFolderChildrens;
              startFolder.Status = sopfolder.Status;
  
              db.Entry(startFolder).State = EntityState.Modified;
  
              db.SaveChanges();
              return Content("true");
          }
  </code></pre>
  
  <p>However this is not working. The model is not updated at all. If I shift the "entityState.Modified" before the modifications, it just creates a complete fresh duplicate of my data in the database (modified of course).</p>
  
  <p>Is my approach correct or do I have to go a different path? What am I missing here? I guess there is another "hidden" id which lets the EF map the entities to the db entries but I am not sure about this. Thanks for help!</p>
  
  <p>UPDATE: 
  Instead of creatinga new instance of SopFolder I also tried <code>db.SopFolders.Find(sopfolder.Id)</code> and this works for entries with no children. If I have entities with children, it creates a duplicate.</p>
  
  <p>Regards,
  Marcus</p>