title: Exception thrown with Entity Framework adding new row to the DB
body: <p>I've been trying for a while to debug this and express what I want to do in different ways, but am having no luck.  I don't know a whole lot about the entity framework, and I inherited this code from another developer who's no longer around so I don't know a whole lot about the model.  Perhaps someone can at least get me pointed in the right direction.  Here's my code:</p>
  
  <pre><code>//Append note to project notes too
  task.TPM_PROJECTVERSIONReference.Load();
  TPM_PROJECTVERSIONNOTES newNote = new TPM_PROJECTVERSIONNOTES();
  newNote.TS = System.DateTime.Now;
  newNote.TPM_USER = SessionHandler.LoginUser;
  newNote.NOTES = task.NOTES;
  newNote.PROJECTID = this.ProjectId;
  newNote.VERSIONID = this.VersionId;
  task.TPM_PROJECTVERSION.TPM_PROJECTVERSIONNOTES.Add(newNote); //&lt;-- Exception
  </code></pre>
  
  <p>I have "task", which points to a project version it belongs to.  These projects have a bunch of notes.  I want to add a new note to the task's project.  However, I get an exception on the last line:</p>
  
  <blockquote>
    <p>System.InvalidOperationException was unhandled by user code<br>
    Message=The relationship between the two objects cannot be
    defined because they are attached to different ObjectContext objects.<br>
    Source=System.Data.Entity</p>
  </blockquote>
  
  <p>This seems like it should be a pretty simple thing.  Is this not the right way to do this?  Thanks!</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Ok I've removed ALL other code from the function and created a brand new context.  Here's the entire function now from start to finish:</p>
  
  <pre><code>//Append note to project notes too
  using (TPMEntities context = new TPMEntities(General.EntityName()))
  {
     TPM_PROJECTVERSIONNOTES newNote = context.TPM_PROJECTVERSIONNOTES.CreateObject();
     newNote.TS = System.DateTime.Now;
     newNote.TPM_USER = SessionHandler.LoginUser;
     newNote.NOTES = this.txtTaskNotes.Text;
     TPM_PROJECTVERSION version = (from pv in context.TPM_PROJECTVERSION
                                   where pv.PROJECTID == this.ProjectId &amp;&amp; pv.VERSIONID == this.VersionId
                                   select pv).First();
  
     version.TPM_PROJECTVERSIONNOTES.Add(newNote);
     context.SaveChanges();
  }
  </code></pre>
  
  <p>Still, I get the same exception:</p>
  
  <pre><code>System.InvalidOperationException was unhandled by user code
    Message=The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
    Source=System.Data.Entity
  </code></pre>
  
  <p>I simply can't understand how there can be two contexts?  I'm using "context" every single place in the code.  How can the Entity Framework make it so difficult to simply add a single row into my database?</p>