title: Violation of Primary Key when trying to add entity with foreign keys
body: <p>I'm using Entity Framework 5 with a code first approach.</p>
  
  <p>I'm trying to do a testing system. It has five classes with one-to-one and one-to-many relationships. One Test has one TestInfo, one User has many TestResults, one TestResult has one TestInfo and many QuestionResults. Here they are (without some simple value-type properties):</p>
  
  <pre><code>public class TestInfo
  {
      [Key]
      public virtual string Name { get; set; }
      public virtual TimeSpan Duration { get; set; }
  }
  
  public class Test
  {
      [Key]
      public virtual int TestId { get; set; }
      public virtual TestInfo Info { get; set; }
      //some other stuff
      //...
  }
  
  public class User
  {
      [Key]
      public virtual string Login { get; set; }
  
      List&lt;TestResult&gt; _results = new List&lt;TestResult&gt;();
      public virtual List&lt;TestResult&gt; Results
      {
          get { return _results; }
          set { _results = value; }
      }
      //...
  }
  
  public class TestResult
  {
      [Key]
      public virtual int TestResultId { get; set; }
      public virtual TestInfo TestInfo { get; set; }
      //...
  
      private List&lt;QuestionResult&gt; _questionResults = new List&lt;QuestionResult&gt;();
      public virtual List&lt;QuestionResult&gt; QuestionResults
      {
          get { return _questionResults; }
          set { _questionResults = value; }
      }
  }
  
  public class QuestionResult
  {
      [Key]
      public virtual int QuestionResultId { get; set; }
      //...
  }
  </code></pre>
  
  <p>My context:</p>
  
  <pre><code>class TestContext : DbContext
  {
      public DbSet&lt;User&gt; Users { get; set; }
      public DbSet&lt;Test&gt; Tests { get; set; }
  }
  </code></pre>
  
  <p>I'm trying to add new TestResult to existing User for existing Test (TestInfo is the same):</p>
  
  <pre><code>public void AddTestResult(TestResult result)
  {
      User user = _context.Users.Include(u =&gt; u.Results).FirstOrDefault(u =&gt; u.Login == _currentLogin);
      TestInfo existingTestInfo = _context.Tests.Where(t =&gt; t.Info.Name == result.TestInfo.Name).FirstOrDefault().Info;
      result.TestInfo = existingTestInfo;
      user.Results.Add(result);
      _context.SaveChanges();
  }
  </code></pre>
  
  <p>When I'm doing it this way, EF throws an exception:</p>
  
  <blockquote>
    <p>{"Violation of PRIMARY KEY constraint 'PK_dbo.TestInfoes'. Cannot insert duplicate key in object 'dbo.TestInfoes'. The duplicate key value is (First test).\r\nThe statement has been terminated."}</p>
  </blockquote>
  
  <p>If I remove QuestionResults property from TestResult class, all works fine. It seems strange for me.
  What am I doing wrong?</p>