title: Having a hard time with Entity Framework detached POCO objects
body: <p>I want to use EF DbContext/POCO entities in a detached manner, i.e. retrieve a hierarchy of entities from my business tier, make some changes, then send the entire hierarchy back to the business tier to persist back to the database. Each BLL call uses a different instance of the DbContext. To test this I wrote some code to simulate such an environment.</p>
  
  <p>First I retrieve a <code>Customer</code> plus related <code>Orders</code> and <code>OrderLines</code>:-</p>
  
  <pre><code>Customer customer;
  using (var context = new TestContext())
  {
      customer = context.Customers.Include("Orders.OrderLines").SingleOrDefault(o =&gt; o.Id == 1);
  }
  </code></pre>
  
  <p>Next I add a new <code>Order</code> with two <code>OrderLines</code>:-</p>
  
  <pre><code>var newOrder = new Order { OrderDate = DateTime.Now, OrderDescription = "Test" };
  newOrder.OrderLines.Add(new OrderLine { ProductName = "foo", Order = newOrder, OrderId = newOrder.Id });
  newOrder.OrderLines.Add(new OrderLine { ProductName = "bar", Order = newOrder, OrderId = newOrder.Id });
  customer.Orders.Add(newOrder);
  newOrder.Customer = customer;
  newOrder.CustomerId = customer.Id;
  </code></pre>
  
  <p>Finally I persist the changes (using a new context):-</p>
  
  <pre><code>using (var context = new TestContext())
  {
      context.Customers.Attach(customer);
  
      context.SaveChanges();
  }
  </code></pre>
  
  <p>I realise this last part is incomplete, as no doubt I'll need to change the state of the new entities before calling SaveChanges(). Do I Add or Attach the customer? Which entities states will I have to change?</p>
  
  <p>Before I can get to this stage, running the above code throws an Exception:</p>
  
  <blockquote>
    <p>An object with the same key already exists in the ObjectStateManager.</p>
  </blockquote>
  
  <p>It seems to stem from not explicitly setting the ID of the two <code>OrderLine</code> entities, so both default to 0. I thought it was fine to do this as EF would handle things automatically. Am I doing something wrong?</p>
  
  <p>Also, working in this "detached" manner, there seems to be an lot of work required to set up the relationships - I have to add the new order entity to the <code>customer.Orders</code> collection, set the new order's <code>Customer</code> property, and its <code>CustomerId</code> property. Is this the correct approach or is there a simpler way?</p>
  
  <p>Would I be better off looking at self-tracking entities? I'd read somewhere that they are being deprecated, or at least being discouraged in favour of POCOs.</p>