title: Adding items through navigation and storing in new context
body: <p>I am getting started with EF4 and struggle to understand how I should add objects correctly.
  It is a multitier application where I have a datalayer, which returns my entity. I then in a business layer alter that entity and add objects to its linked objects through navigation. However I seem to run into a problem, when I try to update the entity, when related objects have been added.</p>
  
  <p>So I have something like this:</p>
  
  <p>FirstTypeOfObject: Id, SomeProperty
  SecondTypeOfObject: Id, SomeProperty, FKToFirstTypeOfObject
  ThirdTypeOfObject: Id, SomeProperty, FKToSecondTypeOfObject</p>
  
  <p>So I have a 1 to many to many relationship.</p>
  
  <p>Now in my DAL I retrieve a FirstTypeOfObject:</p>
  
  <pre><code>using(var context = new ObjectContext())
  {
    var first = context.FirstTypeOfObjects
      .Single(i =&gt; i.id = "something")
      .Include(o =&gt; o.SecondTypeOfObjects.Select(s =&gt; s.ThirdKindOfObjects))) 
    return first;
  }
  </code></pre>
  
  <p>I then in my businesslayer add to this object:</p>
  
  <pre><code>ThirdKindOfObject t = new ThirdKindOfObject();
  t.SomeProperty = "test";
  t.Id = Guid.NewGuid();
  first.SecondTypeOfObjects.FirstOrDefault().Add(t);
  </code></pre>
  
  <p>I then call a method in my DAL:</p>
  
  <pre><code>public void UpdateObject(FirstTypeOfObject myObject)
  {
    using(var context = new ObjectContext())
    {
      context.FirstTypeOfObject.Attach(myObject)
      context.ObjectStateManager.ChangeObjectState(myObject, EntityState.Modified);
      context.SaveChanges()
    }
  }
  </code></pre>
  
  <p>But when I update the item I get an error:</p>
  
  <pre><code>An object with a temporary EntityKey value cannot be attached to an object context
  </code></pre>
  
  <p>I don't want to go to the database everytime I need to create a ThirdTypeOfObject, as it might be 100s of objects. Also I would like to pass the entity model around for modification and my DAL doesn't know what have been modified. I don't want my DAL to know of any classes written in the business layer. </p>
  
  <p>Am I doing this as it wasn't intended? Am I just missing out on something?</p>