【发布时间】:2013-12-24 17:23:13
【问题描述】:
如何使用 ASP.Net Web API 2 放置嵌套的 ICollection?我会解释的。
我正在使用带有 Web API 2 的实体框架。我的公司如下:
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; }
}
我有基于 Company 模型的标准生成的 Web API 2 控制器。这是我的 PUT 函数:
// 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);
}
由于默认生成的 PUT 函数中的 db.Entry(company).State = EntityState.Modified; 不起作用,我已将其替换为如上所述的 on another question。
当我发送如下 PUT 调用时,保存名称和 CountryRegion 但不保存组织。
$.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"
}
]
}
});
如何修改我的控制器代码以便组织保存?组织与公司是多对多的。我想也许我可以删除与该公司关联的所有现有组织,然后保存所有新组织,但我对如何真正让这些新组织保存并与该公司关联感到困惑。
【问题讨论】:
标签: asp.net asp.net-mvc entity-framework asp.net-web-api