2

这是情况,我有三个实体,它们具有以下关系:

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

4

2 回答 2

5

经过长时间的搜索和阅读,我终于弄清楚了我打算做什么。我很幸运,创建和保存 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();
    }
于 2012-12-09T06:23:00.950 回答
2

与 add 附加可从提供的实体访问的整个图不同,应用更改仅将更改应用于提供的实体,它也不知道应该修改哪些连接的实体。

您将不得不为每个实体调用应用更改。

于 2012-12-06T09:11:42.743 回答