【发布时间】:2017-03-24 09:07:17
【问题描述】:
我有两个相互关联的模型如下:
public class CoreGoal
{
[Key]
public long CoreGoalId { get; set; }
[Required]
public string Title { get; set; }
public virtual ICollection<Benefit> Benefits { get; set; }
public CoreGoal()
{
}
}
还有
public class Benefit
{
[Key]
public long BenefitId { get; set; }
[Required]
public string What { get; set; }
public long CoreGoalD { get; set; }
[ForeignKey("CoreGoalId")]
public virtual CoreGoal CoreGoal { get; set; }
public Benefit()
{
}
}
我的控制器类中的 UPDATE 方法:
[Route("api/[controller]")]
public class CoreGoalController : Controller
{
private readonly ICoreGoalRepository _coreGoalRepository;
//Controller
public CoreGoalController(ICoreGoalRepository coreGoalRepository) {
_coreGoalRepository = coreGoalRepository;
}
...
//Update
[HttpPut("{id}")]
public IActionResult Update(long id, [FromBody] CoreGoal item)
{
if (item == null || item.CoreGoalId != id)
{
return BadRequest();
}
var coreGoal = _coreGoalRepository.Find(id);
if (coreGoal == null)
{
return NotFound();
}
coreGoal.Title = item.Title;
coreGoal.Benefits = item.Benefits;
_coreGoalRepository.UpdateCoreGoal(coreGoal);
return new NoContentResult();
}
}
还有我的仓库:
public class CoreGoalRepository : ICoreGoalRepository
{
private readonly WebAPIDataContext _db;
public CoreGoalRepository(WebAPIDataContext db)
{
_db = db;
}
...
//Find specific
public CoreGoal Find(long key)
{
return _db.CoreGoals.FirstOrDefault(t => t.CoreGoalId == key);
}
//Update specific
public void UpdateCoreGoal(CoreGoal coreGoal)
{
_db.CoreGoals.Update(coreGoal);
_db.SaveChanges();
}
}
我的问题是它是编写 UPDATE 方法的正确方法吗? 考虑当我发出 GET 请求时,我会返回:
[
{
"coreGoalId": 1,
"title": "Goal 1",
"benefits": [
{
"benefitId": 1,
"what": "Benefit 1",
"coreGoalD": 0
}
]
}
]
现在我想更新这个核心目标,所以我做了一个 PUT 请求如下:
它给了我
An exception of type 'Microsoft.EntityFrameworkCore.DbUpdateException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code
我是否发送了错误的请求,或者我在控制器或存储库中错误地实现了该方法?为什么我不能在一个请求中只更新部分父实体或子实体?
【问题讨论】:
标签: asp.net-core asp.net-core-mvc entity-framework-core