gpt4 book ai didi

c# - EF 5 更新 N 级深度对象图?

转载 作者:行者123 更新时间:2023-11-30 20:04:01 24 4
gpt4 key购买 nike

情况是这样的,我有三个实体,它们之间的关系如下:

-Team one-to-one TeamContact
-TeamContact one-to-one TeamAddress

我成功地创建、添加和保存了这些对象,没有任何问题。但是,当我尝试创建一个编辑方法时,只有父对象在修改后被保存。看看下面我到目前为止所拥有的;

我的 Db 类中的 Save 方法

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 级深层对象?

最佳答案

经过长时间的搜索和阅读,我终于明白了我打算做什么。我很幸运,创建和保存 N 级深层对象图并不像更新这些对象那么难。无论如何,在阅读 Danny Varod 的评论后,我决定回去阅读更多关于 DbContext 的内容。 .下面是我试图做的,我也很抱歉我正在使用相同的方法来保存新对象:

public void SaveTeam(Team team)
{
if (team.Id == 0)
{
context.Teams.Add(team);
}
else if (team.Id > 0)
{
//This Updates N-Level deep Object grapgh
var currentTeam = context.Teams
.Include(c => c.TeamContact)
.Include(a => a.TeamContact.TeamAddress)
.Single(t => t.Id == team.Id);

context.Entry(currentTeam).CurrentValues.SetValues(team);
currentTeam.TeamContact.TeamAddress = team.TeamContact.TeamAddress;
currentTeam.TeamContact = team.TeamContact;
}
context.SaveChanges();
}

关于c# - EF 5 更新 N 级深度对象图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13740005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com