title: Web API PUT nested ICollection
body: <p>How do I PUT a nested ICollection using ASP.Net Web API 2? I'll explain.</p>
  
  <p>I'm using Entity Framework with Web API 2. I have a Company as follows:</p>
  
  <pre><code>public class Company
  {
      public int ID { get; set; }
  
      [Required]
      public string Name { get; set; }
  
      ..
  
      public virtual CountryRegion CountryRegion { get; set; }
      public virtual ICollection&lt;Organization&gt; Organizations { get; set; }
  }
  </code></pre>
  
  <p>I have the standard generated Web API 2 controller based of the Company model. Here is my PUT function:</p>
  
  <pre><code>// PUT api/Company/5
  public IHttpActionResult PutCompany(int id, Company company)
  {
      if (!ModelState.IsValid)
      {
          return BadRequest(ModelState);
      }
  
      if (id != company.ID)
      {
          return BadRequest();
      }
  
      var entityToUpdate = db.Companies.Find(id);
      db.Entry&lt;Company&gt;(entityToUpdate).CurrentValues.SetValues(company);
      db.Entry&lt;Company&gt;(entityToUpdate).State = EntityState.Modified;
  
      db.Entry&lt;CountryRegion&gt;(entityToUpdate.CountryRegion).CurrentValues.SetValues(company.CountryRegion);
  
      try
      {
          db.SaveChanges();
      }
      catch (DbUpdateConcurrencyException)
      {
          if (!CompanyExists(id))
          {
              return NotFound();
          }
          else
          {
              throw;
          }
      }
  
      return StatusCode(HttpStatusCode.NoContent);
  }
  </code></pre>
  
  <p>Since <code>db.Entry(company).State = EntityState.Modified;</code> from the default generated PUT function does not work I have replaced that as discussed <a href="https://stackoverflow.com/questions/6033638/an-object-with-the-same-key-already-exists-in-the-objectstatemanager-the-object">on another question</a> as seen above. </p>
  
  <p>When I send a PUT call like follows Name and CountryRegion save but not Organizations.</p>
  
  <pre><code>$.ajax({
      type: "PUT",
      url: "/api/company/2",
      data: {
          ID:2, 
          Name: "Test Company", 
          CountryRegion: {
              ID: 2, 
              Name: "United States"
          }, 
          Organizations: [
              {
                  ID: 10,
                  Name: "Test Org"
              },
              {
                  ID: 22,
                  Name: "Test Org 2"
              }
          ]
      }
  });
  </code></pre>
  
  <p>How can I modify my controller code so that Organizations saves? Organization is many to many with Company. I thought perhaps I could just delete all of the existing Organizations associated to this Company and then save all the new ones but I'm then confused by how I can actually get those new Organizations to save and associate with the Company.</p>