开发者

Self-tracking Entity - Tries to insert an unchanged entity when adding to collection

Using EF4 Self-tracking entities.

I have a "User" entity that has a collection of "Groups" the user can belong to. I want to add/remove some "Groups" to this user given just a list of Group IDs.

    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();
        }
    }

The result in this method throws an error at Context.SaveChanges(). The error reports that "Group" entities does not allow null for Name property.

This is expected if I were INSERTING new groups, but 开发者_高级运维thats obviously not what I'm trying to do. How can I fix this problem?


You actually ARE inserting. By creating a new group and adding it to the collection in essense you are saying, here is a new group now add it. You need to load the group from the database first to activate tracking on it. then add the group to the users group collection.

amit_g's solution will work but will result in several DB calls ( A DB call per group). I would pre load all the groups up front


Try it with

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜