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

时间:2012-12-06 08:54:26

标签: c# asp.net-mvc-4 code-first entity-framework-5 asp.net-4.5

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

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

2 个答案:

答案 0 :(得分: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();
    }

答案 1 :(得分:2)

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

您必须为每个实体调用应用更改。