How do I PUT a nested ICollection using ASP.Net Web API 2? I'll explain.
I'm using Entity Framework with Web API 2. I have a Company as follows:
public class Company
{
public int ID { get; set; }
[Required]
public string Name { get; set; }
..
public virtual CountryRegion CountryRegion { get; set; }
public virtual ICollection<Organization> Organizations { get; set; }
}
I have the standard generated Web API 2 controller based of the Company model. Here is my PUT function:
// 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<Company>(entityToUpdate).CurrentValues.SetValues(company);
db.Entry<Company>(entityToUpdate).State = EntityState.Modified;
db.Entry<CountryRegion>(entityToUpdate.CountryRegion).CurrentValues.SetValues(company.CountryRegion);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!CompanyExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
Since db.Entry(company).State = EntityState.Modified;
from the default generated PUT function does not work I have replaced that as discussed on another question as seen above.
When I send a PUT call like follows Name and CountryRegion save but not Organizations.
$.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"
}
]
}
});
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.