title: EF6 merge entity from WebApi
body: <p>I've been tasked with the glorious mission of modernizing a CRUD system (Ironic). I'm using EF 6.1.1 and WebApi. I send the Entity using a DTO (dynamic object for now will create a static type when all is working, will also make the calls <code>async</code>)</p>
  
  <pre><code>[HttpGet]
  public dynamic Get(int id)
  {
      var p = personRepository.Get(id);
  
      return new
      {
          p.PersonId,
          p.BirthYear,
          p.DeathYear,
          p.Comment,
          PersonNames = p.PersonNames.Select(pn =&gt; new { pn.PersonId, pn.PersonNameId, pn.NameTypeId, pn.Firstname, pn.Prefix, pn.Surname })
      };
  }
  </code></pre>
  
  <p>I then update fields on the <code>Person</code> object or add/remove/update <code>PersonNames</code> collection using <code>Knockout</code> and <code>ko.mapping</code></p>
  
  <p>I post the result to this WebApi method</p>
  
  <pre><code>[HttpPost]
  public void Post([FromBody]Person person)
  {
      personRepository.Merge(person);
  }
  </code></pre>
  
  <p>All the id's etc are correct, in <code>personRepository.Merge</code> i've tried </p>
  
  <pre><code>public void Merge(Person person)
  {
      db.People.AddOrUpdate(person);
      db.SaveChanges();
  } 
  </code></pre>
  
  <p>This works for the fields directly on the personobject, but it does not work with add/remove/update on the <code>PersonNames</code></p>
  
  <p>Can I support this without writing manual merge code?</p>
  
  <p><strong>Solution</strong>
  Ended up doing this</p>
  
  <pre><code>public void Merge(Person person)
  {
      db.People.AddOrUpdate(person);
      var existingNames = db.PersonNames.Where(pn =&gt; pn.PersonId == person.PersonId).ToList();
      var deleted = existingNames.Where(pn =&gt; person.PersonNames.All(d =&gt; d.PersonNameId != pn.PersonNameId));
      db.PersonNames.RemoveRange(deleted);
  
      foreach (var name in person.PersonNames)
      {
          db.PersonNames.AddOrUpdate(name);
      }
      db.SaveChanges();
  }
  </code></pre>