自跟踪实体 - 尝试在添加到集合时插入未更改的实体

时间:2011-03-15 21:58:26

标签: entity-framework self-tracking-entities

使用EF4自我跟踪实体。

我有一个“用户”实体,其中包含用户可以属于的“群组”集合。我只想给出一个组ID列表,为这个用户添加/删除一些“组”。

    public void UserAddGroups(int userID, List<int> groups)
    {
        var user = Context.Users.Include("Groups").FirstOrDefault(u => u.ID == userID);
        if (user != null)
        {
            // Iterate through the groups that the user already belongs to.
            foreach (var group in user.Groups.ToList())
            {
                // Remove any groups from the user if the new list does not have it.
                if (!groups.Contains(group.ID)) user.Groups.Remove(group);
                // Else remove it from the list of new groups to avoid duplication.
                else groups.Remove(group.ID);
            }
            // Iterate through the group list and add it to the user's list
            // (only a stubby is created)
            foreach (var group in groups) user.Groups.Add(new Group { ID = group }.MarkAsUnchanged());
            Context.Users.ApplyChanges(user);
            Context.SaveChanges();
        }
    }

此方法的结果会在Context.SaveChanges()处引发错误。该错误报告“组”实体不允许null属性为Name

如果我 INSERTING 新组,这是预期的,但这显然不是我想要做的。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

你实际上正在插入。通过创建一个新组并将其添加到您所说的essense集合中,这里有一个新组现在添加它。您需要首先从数据库加载组以激活对其的跟踪。然后将该组添加到用户组集合。

amit_g的解决方案可以正常工作,但会导致多个数据库调用(每组一次数据库调用)。我会预先加载所有组

答案 1 :(得分:1)

尝试

user.Groups.Add(Context.Groups.FirstOrDefault(g => g.ID == group));