title: Entity Framework POCO with Foreign keys
body: <p>My question can better be explained via example code. I am using POCO with change tracking proxies that is generated by the C# POCO generator by default. Please see below.</p>
  
  <p>Assume you have Movie, MusicDirector and Director in the database and the relationship between them is a Director &amp; MusicDirector can direct multiple movies and a movie can have only one Director and MusicDirector. Since I am a new user and cannot post images, here is my db structure. </p>
  
  <p>Movie table has MovieId, Name,MusicDirectorId,DirectorId</p>
  
  <p>Director table has DirectorId, Name</p>
  
  <p>MusicDirector table has MusicDirectorId, Name    </p>
  
  <p>Here is the link to the diagram. <a href="http://i.stack.imgur.com/ce49r.png" rel="nofollow">http://i.stack.imgur.com/ce49r.png</a>.</p>
  
  <p>I am trying to insert a new movie and the director and musicdirector "already exists" in the db. Below is my code. </p>
  
  <pre><code>Movie movie = new Movie();            
          movie.Name = "Movie1";
          movie.Director = new Director() { Name = "DirectorA" };           
          movie.MusicDirector = new MusicDirector() { Name = "MusicDirectorA" };
  
          using (TestEFEntities ctx = new TestEFEntities())
          {
              movie.Director = ctx.Directors.Where(x =&gt; x.Name == movie.Director.Name).FirstOrDefault();
              movie.MusicDirector = ctx.MusicDirectors.Where(x =&gt; x.Name == movie.MusicDirector.Name).FirstOrDefault();                                    
              ctx.Movies.AddObject(movie);                    
              ctx.SaveChanges();
          }
  </code></pre>
  
  <p>Now when I do this, MusicDirector record is added again even though it is overwritten by the record from the db. You may think why I am keeping this line  movie.Director = new Director() { Name = "DirectorA" }; initially, it is an Asp.net MVC app where Movie object is bound with the director and musicdirector names the user adds. So, the first 4 lines are done implicitly by MVC and think all the other lines are in the service layer. Am I missing something as this is a very basic scenario and the framework should handle it? Of course, one solution to correct this problem is to create a new Movie object and assign the records from db which I don't want to do as I have to copy all the properties from the movie object sent by controller. How can I solve this problem? </p>
  
  <p>Also this works correctly in Self-Tracking Entities. Is this some kind of a limitation to POCO and it would be great if someone can explain the behavior? </p>