title: How to relate objects from multiple contexts using the Entity Framework
body: <p>I am <strong>very</strong> new to the entity framework, so please bear with me...</p>
  
  <p>How can I relate two objects from different contexts together?</p>
  
  <p>The example below throws the following exception:</p>
  
  <blockquote>
    <p>System.InvalidOperationException: The
    relationship between the two objects
    cannot be defined because they are
    attached to different ObjectContext
    objects.</p>
  </blockquote>
  
  <pre><code>void MyFunction()
  {
      using (TCPSEntities model = new TCPSEntities())
      {
          EmployeeRoles er = model.EmployeeRoles.First(p=&gt;p.EmployeeId == 123);
          er.Roles = GetDefaultRole();
          model.SaveChanges();
       }
  }
  
  private static Roles GetDefaultRole()
  {
      Roles r = null;
      using (TCPSEntities model = new TCPSEntities())
      {
          r = model.Roles.First(p =&gt; p.RoleId == 1);
      }
      return r;
  }
  </code></pre>
  
  <p>Using one context is not an option because we are using the EF in an ASP.NET application.</p>