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?