title: How to prevent Entity Framework from adding referenced objects to database on SaveChanges?
body: <p>I have quite a simple situation. I've got 3 objects:</p>
  
  <ul>
  <li>an object called <code>TrainingConsultant</code> which is not yet saved to the database</li>
  <li>an object called <code>Training</code> which was recently saved to the database and its <code>EntityState</code> is <code>Detatched</code>.</li>
  <li>an object called <code>Consultant</code> which was recently loaded the from database and its <code>EntityState</code> is <code>Detatched</code>.</li>
  </ul>
  
  <p>I need to save the <code>TrainingConsultant</code> object with referenced <code>Consultant</code> and <code>Training</code>, so that in the database all the required fields and foreign keys are filled in properly.</p>
  
  <p>The problem is that until I call <code>context.TrainingConsultants.AddObject(trainingConsultant);</code>, everything is in the <code>Detached</code> state. After that, both <code>training</code> and <code>consultant</code> have their <code>EntityState</code> changed to <code>Added</code>, so <code>context.SaveChanges()</code> tries to add both <code>training</code> and <code>consultant</code> to the database before adding <code>traingingConsultant</code>. It fails because <code>Consultant</code> already exists in the database, so does <code>consultant</code>.</p>
  
  <p>How can I fix this so both <code>Consultant</code> and <code>Training</code> won't get saved but still get referenced? Keep in mind that I am assigning those 2 referenced objects somewhere else in code:</p>
  
  <pre><code>trainingConsultant.Training = training;
  trainingConsultant.Consultant = consultant;
  </code></pre>
  
  <p>So when it comes to saving any changes would require me to save objects temporary, then set <code>TrainingConsultant.Training</code> and <code>TrainingConsultant.Consultant</code> to <code>null</code>?</p>
  
  <pre><code>using (var context = new Entity(Settings.sqlDataConnectionDetails))
  {
      context.TrainingConsultants.AddObject(trainingConsultant);
      context.SaveChanges();
  }
  </code></pre>