title: Mimicking SQL Insert Trigger with LINQ-to-SQL
body: <p>Using LINQ-to-SQL, I would like to automatically create child records when inserting the parent entity.  Basically, mimicking how an SQL Insert trigger would work, but in-code so that some additional processing can be done.</p>
  
  <p>The parent has an association to the child, but it seems that I cannot simply add new child records during the DataContext's <code>SubmitChanges()</code>.</p>
  
  <p>For example,</p>
  
  <pre><code>public partial class Parent 
  {
      partial void OnValidate(System.Data.Linq.ChangeAction action)
      {
          if(action == System.Data.Linq.ChangeAction.Insert)
          {
              Child c = new Child();
              ... set properties ...
              this.Childs.Add(c);
          }
      }
  }
  </code></pre>
  
  <p>This would be ideal, but unfortunately the newly created <code>Child</code> record is not inserted to the database.  Makes sense, since the DataContext has a list of objects/statements and probably doesn't like new items being added in the middle of it.</p>
  
  <p>Similarly, intercepting the <code>partial void InsertParent(Parent instance)</code> function in the DataContext and attempting to add the <code>Child</code> record yields the same result - no errors, but nothing added to the database.</p>
  
  <p>Is there any way to get this sort of behaviour without adding code to the presentation layer?</p>
  
  <p><strong>Update:</strong>
  Both the <code>OnValidate()</code> and <code>InsertParent()</code> functions are called from the DataContext's <code>SubmitChanges()</code> function.  I suspect this is the inherent difficulty with what I'm trying to do - the DataContext will not allow additional objects to be inserted (e.g. through <code>InsertOnSubmit()</code>) while it is in the process of submitting the existing changes to the database.</p>
  
  <p>Ideally I would like to keep everything under one Transaction so that, if any errors occur during the insert/update, nothing is actually changed in the database.  Hence my attempts to mimic the SQL Trigger functionality, allowing the child records to be automatically inserted through a single call to the DataContext's <code>SubmitChanges()</code> function.</p>