title: Help needed for LINQ To SQL operations (insert/update) with nested POCO's
body: <p>Ok well I've been trying to convert my model to use LINQ but didn't want to throw away my current DTO's and their interfaces which are scattered through the domain.</p>
  
  <p>I managed to find this blog post which has outlined the process quite nicely:</p>
  
  <p><a href="http://www.sidarok.com/web/blog/content/2008/10/14/achieving-poco-s-in-linq-to-sql.html" rel="noreferrer">Achieving POCOs in LINQ To SQL</a></p>
  
  <p>I have the managed to get the retrieval of records to objects working properly, however, due to the nested nature of my my model, I can't seem to get addition working for the child objects. That is, if I create a child object, and set the reference to the desired parents object, LINQ to SQL still throws an exception stating the child's reference to the parent is null. If I attempt to add a plain old parent object, it succeeds, but adding child objects directly fails</p>
  
  <p>Here is my failing test:</p>
  
  <pre><code>    [Test]
      public void AddSelectionShouldAddSelectionToMarket()
      {
          Market market = (Market) new Repository().GetMarket(1);
  
          Selection selection = new Selection();
          selection.Market = market;
  
          new Repository().AddSelection(selection);
  
          Assert.IsTrue(selection.SID &gt; 0);
      }
  </code></pre>
  
  <p>Here is the error message:</p>
  
  <p>System.InvalidOperationException: An attempt was made to remove a relationship between a Market and a Selection. However, one of the relationship's foreign keys (Selection.MID) cannot be set to null.</p>
  
  <p>The relevant parts of the 2 objects:</p>
  
  <pre><code>[DataContract]
  public class Selection : ISelection
  {
      private int mID;
      [DataMember]
      public int MID
      {
          get { return this.mID; }
          set { this.mID = value; }
      }
  
      private Market market;
      [DataMember]
      public Market Market
      {
          get { return this.market; }
          set
          {
              this.market = value;
              this.mID = value.MID;
          }
      }
  }
  
  [DataContract]
  public class Market : IMarket
  {
      private int mID;
      [DataMember]
      public int MID
      {
          get { return this.mID; }
          protected set { this.mID = value; }
      }
  
      private List&lt;Selection&gt; selections;
      [DataMember]
      public List&lt;Selection&gt; Selections
      {
          get { return this.selections; }
          set
          {
              this.selections = value;
              // For LINQ
              foreach (Selection selection in selections)
              {
                  selection.MID = mID;
                  selection.Market = this;
              }
          }
      }
  }
  </code></pre>
  
  <p>My DA code:</p>
  
  <pre><code>        MarketsDataContext context = new MarketsDataContext();
  
          DataLoadOptions options = new DataLoadOptions();
          options.LoadWith&lt;Selection&gt;(s =&gt; s.Prices);
          options.LoadWith&lt;Market&gt;(m =&gt; m.Selections);
  
          context.LoadOptions = options;
          return context;
  </code></pre>
  
  <p>and;</p>
  
  <pre><code>    public void AddSelection(ISelection selection)
      {
          using (MarketsDataContext context = MarketsDataContext.GetContext())
          {
              context.Selections.InsertOnSubmit((Selection) selection);
              context.SubmitChanges();
          }
      }
  </code></pre>
  
  <p>And finally my XML mapping:</p>
  
  <pre><code>  &lt;Table Name="dbo.Markets" Member="Markets"&gt;
      &lt;Type Name="Market"&gt;
        &lt;Column Name="MID" Member="MID" Storage="mID" DbType="Int NOT NULL" IsPrimaryKey="true" IsDbGenerated="true" AutoSync="OnInsert" /&gt;
        &lt;Association Name="FK_Market-Selections" Member="Selections" Storage="selections" ThisKey="MID" OtherKey="MID" DeleteRule="NO ACTION"  /&gt;
      &lt;/Type&gt;
    &lt;/Table&gt;
  
    &lt;Table Name="dbo.Selections" Member="Selections"&gt;
      &lt;Type Name="Selection"&gt;
        &lt;Column Name="SID" Member="SID" Storage="sID" DbType="Int NOT NULL" IsPrimaryKey="true" IsDbGenerated="true" AutoSync="OnInsert" /&gt;
        &lt;Column Name="MID" Member="MID" Storage="mID" DbType="Int NOT NULL" /&gt;
        &lt;Association Name="FK_Market-Selections" Member="Market" Storage="market" ThisKey="MID" OtherKey="MID" IsForeignKey="true" /&gt;
      &lt;/Type&gt;
    &lt;/Table&gt;
  </code></pre>
  
  <p>So, can anyone point me in the right direction? I've been searching for hours...</p>
  
  <p>Edit:</p>
  
  <p>Here's my stacktrace for my test failure:</p>
  
  <pre><code>at System.Data.Linq.ChangeTracker.StandardChangeTracker.StandardTrackedObject.SynchDependentData()
  at System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list)
  at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
  at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
  at System.Data.Linq.DataContext.SubmitChanges()
  at BetMax.DataModel.Repository.AddSelection(ISelection selection) in Repository.cs: line 68
  at BetMax.DataModel.Test.ModelTest.AddSelectionShouldAddSelectionToMarket() in ModelTest.cs: line 65 
  </code></pre>
  
  <p>And my GetMarket method:</p>
  
  <pre><code>    public IMarket GetMarket(int MID)
      {
          Market market;
          using (MarketsDataContext context = MarketsDataContext.GetContext())
          {
              market = context.Markets.Single(m =&gt; m.MID == MID);
          }
          return market;
      }
  </code></pre>
  
  <p>Edit 2:</p>
  
  <p>Well, adding </p>
  
  <pre><code>DeleteOnNull="true"
  </code></pre>
  
  <p>to Selections foreign key in the XML mapping has removed the foreign key error, but now I'm getting a null reference on one of Selections's child objects, saying its reference to Selection is null even though Selection is being initialised with none of its variables set (outside the foreign keys). I even tried creating a child object, and set its references correctly but am still getting this error:</p>
  
  <pre><code>System.NullReferenceException: Object reference not set to an instance of an object.
  at BetMax.DTO.Price.set_Selection(Selection value) in Price.cs: line 25
  at System.Data.Linq.Mapping.PropertyAccessor.Accessor`3.SetValue(ref T instance, V value)
  at System.Data.Linq.Mapping.MetaAccessor`2.SetBoxedValue(ref Object instance, Object value)
  at System.Data.Linq.ChangeProcessor.ClearForeignKeysHelper(MetaAssociation assoc, Object trackedInstance)
  at System.Data.Linq.ChangeProcessor.ClearForeignKeyReferences(TrackedObject to)
  at System.Data.Linq.ChangeProcessor.PostProcessUpdates(List`1 insertedItems, List`1 deletedItems)
  at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
  at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
  at System.Data.Linq.DataContext.SubmitChanges()
  at BetMax.DataModel.Repository.AddSelection(ISelection selection) in Repository.cs: line 68
  at BetMax.DataModel.Test.ModelTest.AddSelectionShouldAddSelectionToMarket() in ModelTest.cs: line 69 
  </code></pre>
  
  <p>Price is another object, constructed in the same that that Selection is related to Market (1 selection has many prices, 1 market has many selections) etc etc.</p>