title: Problems trying to attach a new EF4 entity to ObjectContext while its entity collection entities are already attached
body: <p>This is somewhat complicated to explain, so please bear with me.</p>
  
  <p>I have an ASP.NET MVC 2 project <strike>that is slowly killing me</strike> in which I'm trying to take form data and translate it into entities to create or update, depending on the context of the situation.  The most relevant parts (pseudo-code):</p>
  
  <pre><code>Entity Game
      Scalar properties
      EntityCollection&lt;Platform&gt; Platforms
  </code></pre>
  
  <p>And the basic workflow is:</p>
  
  <p>Form data -> model bound to a DTO -> mapping the DTO to an EF4 entity with AutoMapper.</p>
  
  <p>It all works well with one exception - I need to create or update the Game entity's Platforms EntityCollection with the raw integer index data contained in the DTO.  So, here's what I've been trying, which does not work:</p>
  
  <pre><code>public AdminController(IArticleRepository articleRepository, IGameRepository gameRepository, INewsRepository newsRepository)
  {
      _articleRepository = articleRepository;
      _gameRepository    = gameRepository;
      _newsRepository    = newsRepository;
  
      Mapper.CreateMap&lt;AdminGameEditModel, Game&gt;()
          .BeforeMap((s, d) =&gt;
          {
              if (d.Platforms.Count &gt; 0)
              {
                  Platform[] existing = d.Platforms.ToArray();
  
                  foreach (var plat in existing)
                  {
                      d.Platforms.Remove(plat);
                  }
              }
  
              foreach (var platId in s.PlatformIDs)
              {
                  var newPlat = _gameRepository.GetPlatform(platId);
  
                  d.Platforms.Add(newPlat); // &lt;-- where it chokes
              }
          })
          .ForMember(dest =&gt; dest.BoxArtPath, opt =&gt; opt.Ignore())
          .ForMember(dest =&gt; dest.IndexImagePath, opt =&gt; opt.Ignore())
          .ForMember(dest =&gt; dest.Cons, opt =&gt; opt.MapFrom(src =&gt; String.Join("|", src.Cons)))
          .ForMember(dest =&gt; dest.Pros, opt =&gt; opt.MapFrom(src =&gt; String.Join("|", src.Pros)))
          .ForMember(dest =&gt; dest.LastModified, opt =&gt; opt.UseValue(DateTime.Now))
          .ForMember(dest =&gt; dest.Platforms, opt =&gt; opt.Ignore());
  }
  </code></pre>
  
  <p>To be specific, I'm getting an exception at the line I highlighted above which says:</p>
  
  <blockquote>
    <p>The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.</p>
  </blockquote>
  
  <p>Some research tells me that this is to be expected, as my fresh Game object has no ObjectContext that it's associated with, and a null context is considered to be a separate context.  See <a href="http://www.code-magazine.com/article.aspx?quickid=0907071&amp;page=4" rel="nofollow">this brief explanation from Julie Lerman</a> for more.</p>
  
  <p>Okay, so being the intrepid person I am, I figured I would simply be able to register my game with the ObjectContext and everything would be fixed.  So, I tried:</p>
  
  <pre><code>Game game = new Game();
  _gameRepository.RegisterGame(game);
  </code></pre>
  
  <p>Where RegisterGame is simply:</p>
  
  <pre><code>public void RegisterGame(Game game)
  {
      _siteDB.Games.AddObject(game);
  }
  </code></pre>
  
  <p>Unfortunately, that did not work.  The same exception is being thrown at the same point.</p>
  
  <p>So, it looks like I'll have to add each Platform's EntityKey to my EntityCollection.  Only problem is, I'm not sure how to do it.</p>
  
  <p>So, any ideas?</p>
  
  <hr>
  
  <p>EDIT: Progress of a sort.  I tried adding just the EntityKeys of the Platform entities, like so:</p>
  
  <pre><code>Mapper.CreateMap&lt;AdminGameEditModel, Game&gt;()
      .BeforeMap((s, d) =&gt;
      {
          if (d.Platforms.Count &gt; 0)
          {
             Platform[] existing = d.Platforms.ToArray();
  
             foreach (var plat in existing)
             {
                  d.Platforms.Remove(plat);
             }
          }
  
          foreach (var platId in s.PlatformIDs)
          {
              var newPlat = _gameRepository.GetPlatform(platId);
  
              d.Platforms.Add(new Platform { EntityKey = newPlat.EntityKey });
          }
      })
  </code></pre>
  
  <p>And it removes the 'two different ObjectContexts' exception.  The problem is that I'm getting the following exception if I try to add or attach the new Game entity to my context:</p>
  
  <blockquote>
    <p>An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.</p>
  </blockquote>
  
  <p>Unfortunately, the exception doesn't specify <em>which</em> object it is, but I'm betting it's one of the Platform objects, since they already exist and I'm merely trying to forge a new relationship between the two.</p>
  
  <p>So, the question remains: how the hell does one make a new entity and populate its EntityCollection&lt;> property with existing entities?  I can't be the only person who ever wanted to create a new entity and create new many-to-many relationships between it and existing entities, right?</p>