LINQ to SQL not inserting child objects correctly RRS feed

  • Question

  • If have an object hierarchy like this:

     - B
        - C
    where each A can have multiple Bs and each B multiple Cs.

    I can use LINQ to SQL to insert my A using dataContext.As.InsertOnSubmit(myA) and it correctly inserts all the child objects as well. So far so good.

    The problem is when I want to update an A that I have already saved by adding a new B (together with its Cs) to the A.

    I'm using detatched entity support to do the update. So I load the original A from a read-only data context, then sometime later I attach it to a writeable data context. I then attach all the Bs and their Cs.

    For any new Bs, I then do an InsertOnSubmit.

    Now, when I call Submit, my new Bs are inserted into the database but not their child Cs. I confirmed what I saw by calling GetChangeSet() before Submit, and the only insert operation is for the Bs.

    I can make this work by also calling InsertOnSubmit for all the child Cs in the inserted B.

    My question is then, why is it that in the first place I only need to call InsertOnSubmit for the root object to have all the children submitted, but later on, doing the same thing for the one level down the hierarchy doesn't work?

    Tuesday, June 23, 2009 3:13 PM

All replies