Unable to determine the principal end of the 'MyApp.Data.AAA_BBB' relationship. Multiple added entities may have the same primary key
<p>I have two tables</p>

<pre class="lang-sql prettyprint-override"><code>create table AAA ( AAAKey int primary key, .... )
create table BBB (
  AAAKey int references AAA(AAAKey), -- Foreign key to AAA
  X      int references X  (XKey),
  ....
  primary key (AAA, X))
</code></pre>

<p>And in C#, the classes generated by EF 6.1.3</p>

<pre><code>[Table("dbo.AAA")]
public partial class AAA
{
  public AAA() { BBB = new HashSet&lt;BBB&gt;(); }
  [Key] public int AAAKey { get; set; }
  public virtual ICollection&lt;BBB&gt; BBB { get; set; }
}
[Table("dbo.BBB")]
public partial class BBB
{
  [Key] public int AAAKey { get; set; }
  [Key] public int XKey { get; set; }
  public virtual AAA AAA { get; set; }
}
......
protected override void OnModelCreating(DbModelBuilder medelBuilder)
{
  ....
     modelBuilder.Entity&lt;AAA&gt;()
            .HasMany(e =&gt; e.BBB)
            .WithRequired(e =&gt; e.AAA)
            .HasForeignKey(e =&gt; e.AAAKey)
            .WillCascadeOnDelete(false);
</code></pre>

<p>However, the code raise the execption when running <code>SaveChanges()</code>?</p>

<p><strong>Update:</strong>
The issue is strange that it only occurs for some data. And I sort of find a solution by converting my original <code>foreach (...) {...}; SaveChange()</code> to <code>foreach (.....) { .....; SaveChange(); }</code>. Does it sound a bug of EF? BTW, all the data I tested always have the duplicate key insertion exceptions, which are expected.</p>