title: Confused about attaching/detaching entities in EF
body: <p>Using ASP.NET MVC and Entity Framework, I encounter some attach/detach errors when I need it to write changes to the database.</p>
  
  <p>First here's how I get the records from my repository:</p>
  
  <pre><code>public PublishedApplication GetPublishedApplication(int id)
  {
      return dal.ExecuteFirstOrDefault(
          context.PublishedApplication.Include("Customers")
          .Where(w =&gt; w.Id == id));
  }
  </code></pre>
  
  <p>Note that this is not being detached, and it has MergeOption = AppendOnly.</p>
  
  <p>Another place, I call a method in my repo to attach a customer to the application:</p>
  
  <pre><code>public void AttachCustomer(int applicationId, int customerId)
  {
      var app = new PublishedApplication{ Id = applicationId};
      var customer = new Customer { Id = customerId};
  
      try
      {
          context.AttachTo("PublishedApplication", app);
          context.AttachTo("Customer ", customer );
  
          app.Customers.Add(customer);
  
          context.SaveChanges();
      }
      catch
      {
          throw;
      }
  }
  </code></pre>
  
  <p>This, of course, gives me an error that the objects (app and customer) are already attached to an object context.</p>
  
  <p>So I need to detach my objects in my repository. This is also more correct as I don't need to throw "query related information" around the web. But how can I do this? If I detach the entity in my <code>GetPublishedApplication</code> method, my graph of related data is lost, and I can't afford that. I need that graph elsewhere on my site. Can't use merge option <code>NoTracking</code> either.</p>
  
  <p>So what options do I have?</p>
  
  <p>Thanks in advance!</p>