Adding children to a detached data object RRS feed

  • Question

  • Hi guys,

    I'm relatively new to LINQ and would like to use it in an N-Tier environment. Most of the stuff is working, but I'm having trouble adding child objects to a parent and committing them to the DB.

    Here's what I do:
        // Create the data context
        DOEDataContext ddc = new DOEDataContext();
        ddc.ObjectTrackingEnabled = false;
        // Get the data objects
        Document orig = ddc.Documents.Single(x => ((Document)x).ID == 1);
        Document doc = ddc.Documents.Single(x => ((Document) x).ID == 1);
        ddc = null;     // Thanks, don't need you anymore
        // Go off and do some other work ...
        // Add a new child object
        DocumentRevision docRev = new DocumentRevision();
        docRev.Filename = "LINQ Rawks!!";
        // Come back and commit the whole thing
        ddc = new DOEDataContext();
        ddc.Documents.Attach(doc, orig);
    This works great if I'm changing any of the Document's field values, but the new child object doesn't get saved to the database.

    So, I used the InsertOrSubmit command to insert the new child object manually, but this re-inserts the parent object and all other child objects to the db. Strange.

    Any ideas?
    Tuesday, April 14, 2009 1:12 PM

All replies

  • Would've helped if I read this a few months ago:

    "What this means is that if you plan on using LINQ to SQL like a traditional ORM - forget it. It just doesn't work well. You need to deal with the DataContext and a connected approach." - Rick Strahl.

    MS Fail
    Wednesday, April 15, 2009 3:59 PM
  • After your call to

    ddc.Documents.Attach(doc, orig);

    try this (your original code, just moved after you've told the DataContext about your Document instance)


    or this

    docRev.Document = doc;

    Wednesday, April 15, 2009 4:05 PM
  • When you call Attach, you are telling LINQ to SQL to Attach everything in your object graph. This means that your Document object and everything related to it (including your new child object) is "unchanged."

    If you explicitly call InsertOnSubmit on your child object AFTER you call Attach, then this should work as expected when you call SubmitChanges.

    As for LINQ to SQL in n-tier scenarios, you should also check out the Oxite project for an example of LINQ to SQL in such an environment.
    Thursday, April 16, 2009 1:48 AM