title: Entity Framework: Working with detached objects and attached ones
body: <p>Firstly, let me set out what I'd like to do. Assume I have three types of <code>EntityObject</code>, <code>MetaData</code>, <code>Data1</code> and <code>Data2</code>. <code>MetaData</code> is, as one would expect, has a reference to one instance each of <code>Data1</code> and <code>Data2</code>. Now, for each <code>MetaData</code>, I can calculate a <code>value</code>.</p>
  
  <p>So far so simple. Now, I would like the user to play around with various combinations of <code>Data1</code> and <code>Data2</code>, and see what <code>value</code>s they can get. This obviously requires creation of instances of <code>MetaData</code>. Now, if I don't want to cluter the database with all these entries of <code>MetaData</code>, then I'd like to create the entity objects in the in-memory context without calling a <code>SaveChanges()</code> to write it back to the DB. However, this presents a problem in that whenever I try to access the <code>Data1</code> and <code>Data2</code> references of the in-memory <code>MetaData</code>, I end up with the following exception:</p>
  
  <p><em>InvalidOperationException is unhandled</em></p>
  
  <p><em>The source query for this EntityCollection or EntityReference cannot be returned when the related object is in either an added state or a detached state and was not originally retrieved using the NoTracking merge option.</em>  </p>
  
  <p>If I do as suggested, and "committ" the object to DB, I end up with the clutter problem.</p>
  
  <p>Anyhow, the guilty code looks something like this:</p>
  
  <pre><code>MetaData temp = MetaData.CreateMetaData(0);
  
  MetaData.Data1 = &lt;existing Data1 from context&gt;;
  MetaData.Data2 = &lt;existing Data2 from context&gt;;
  
  //Exception here
  if (!MetaData.Data1Reference.isLoaded)
      MetaData.Data1Reference.Load();
  </code></pre>
  
  <p>It seems <a href="http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/7d00afc3-0f4c-460f-98cc-b2395789fa5b/" rel="nofollow noreferrer">this guy</a> had a similar problem.</p>