这是情况,我有三个实体,它们具有以下关系:
-Team one-to-one TeamContact
-TeamContact one-to-one TeamAddress
我已经成功地创建、添加和保存了这些对象。但是,当我尝试创建编辑方法时,修改后只保存父对象。见下文我到目前为止;
在我的 Db 类中保存方法
public void SaveTeam(Team team)
{
if (team.Id == 0)
{
context.Teams.Add(team);
}
else
{
var model = context.Teams.Find(team.Id);
context.Entry(model).CurrentValues.SetValues(team);
}
context.SaveChanges();
}
编辑方法
[HttpGet]
public ActionResult Edit(int id)
{
var model = _dataSource.Teams.FirstOrDefault(t => t.Id == id);
return View(model);
}
[HttpPost]
public ActionResult Edit(Team team)
{
if (ModelState.IsValid)
{
_dataSource.SaveTeam(team);
return RedirectToAction("Detail", "Team", new { id = team.Id });
}
return View(team);
}
就像我上面说的,我只让我修改父对象,我在这里错过了什么?
试过了
public void SaveTeam(Team team)
{
if (team.Id == 0)
{
context.Teams.Add(team);
}
else
{
//var model = context.Teams.Find(team.Id);
var model = context.Teams.Include(c => c.TeamContact).Single(t => t.Id == team.Id);
context.Entry(model).CurrentValues.SetValues(team);
model.TeamContact = team.TeamContact;
}
context.SaveChanges();
}
尝试上述方法后出现此错误:
Violation of PRIMARY KEY constraint 'PK_dbo.TeamAddresses'. Cannot insert duplicate key in object 'dbo.TeamAddresses'. The duplicate key value is (5).
The statement has been terminated.
底线,如何更新 N 级深度对象?