views:

21

answers:

1

Hello

I'm trying to delete all "Usergroup"s that belongs to one "User" and then add new "Usergroup"s.

    public void SaveUserUsergroups(int userID, int[] UsergroupID)
    {

        User uo = _entities.Users.Where(x => x.UserID == userID).First();

        uo.Usergroups.Load();


        foreach(Usergroup ug in uo.Usergroups)
        {

            uo.Usergroups.Remove(ug);
        }


        int _currentUsergroupID;

        for (int i = 0; i < UsergroupID.Count(); i++)
        {
            _currentUsergroupID = UsergroupID[i];

            uo.Usergroups.Add(_entities.Usergroups.Where(ug => ug.UsergroupID == _currentUsergroupID).First());
        }

        _entities.SaveChanges();

    }

It throws an exception if there are more than 1 usergroup here:

        foreach(Usergroup ug in uo.Usergroups)
        {

            uo.Usergroups.Remove(ug);
        }

How should I fix that?

/M

+2  A: 

You can't modify a collection whilst iterating through it. You can either build up a collection of items that you want to remove and remove them from the relation after the foreach loop or iterate through the collection backwards using a counter like so:

   for (int i = uo.Usergroups.Count - 1; i >= 0; i--)
   {
        uo.Usergroups.Remove(uo.Usergroups.ElementAt(i));
   }
mattythomas2000