none
Trouble moving a record between parent instances RRS feed

  • Question

  • I have a Parent model. Parent has many Childs.

    I have a feature I need to support which is to move all Childs from one Parent to another Parent. I've tried this code:

    Dim p1 as Parent = get from db
    Dim p2 as Parent = get from db

    for each c as Child in p1.childs
      p2.childs.add(c)
      p1.childs.remove(c)
    next

    When I do this however I get an error: "EntitySet was modified during enumeration"

    I tried just setting c.parent_id = p2.id. But the caches get wonky and aren't updated. This is a problem because after moding the childs I need to do some operations on the parent which require it to have all the right data.

    So, how can I do this?

    Thanks.
    Monday, August 10, 2009 4:52 AM

Answers

  • Thanks Damien. I actually solved this on my own last night. I did this:

    p2.childs.AddAll(p1.childs)

    This does exactly what I needed and keeps everything in sync.
    Monday, August 10, 2009 2:34 PM

All replies

  • The actual problem is that you can't modify a collection while you are foreach'ing over it.

    You should be able to:

    Dim newChildren = p1.childs.ToList();
    For Each c as Child in newChildren
      p2.Childs.Add(c)
    Next

    [)amien
    Monday, August 10, 2009 6:26 AM
    Moderator
  • Thanks Damien. I actually solved this on my own last night. I did this:

    p2.childs.AddAll(p1.childs)

    This does exactly what I needed and keeps everything in sync.
    Monday, August 10, 2009 2:34 PM