title: Entity Framework duplicate primary key
body: <p>I'm using Entity Framework 6 and sqlite to store and retrieve some data. When the following code block runs, an exception is thrown on <code>db.SaveChanges()</code>.</p>
  
  <pre><code>using (var db = new RepoDatabase(DBPath))
  {
      var folder1 = new Folder
      {
          Name = "name1",
          Subtitle = "subtitle",
          ParentFolder = null,
          IsHidden = false,
          IsSimple = true,
          QueryOrFilePath = "query"
      };
  
      var folder2 = new Folder
      {
          Name = "name2",
          Subtitle = "subtitle",
          ParentFolder = folder1,
          IsHidden = false,
          IsSimple = true,
          QueryOrFilePath = "query"
      };
      db.Folders.Add(folder1);
      db.Folders.Add(folder2);
      db.SaveChanges();
  }
  </code></pre>
  
  <p>Exception:</p>
  
  <blockquote>
    <p>'System.Data.Entity.Infrastructure.DbUpdateException' occurred in   EntityFramework.dll</p>
    
    <p>Additional information: Unable to determine the principal end of the 'RhythmRepository.Folder_ParentFolder' relationship. Multiple added entities may have the same primary key.</p>
  </blockquote>
  
  <p>From my understanding, this problem often occurs when the ID is used directly for foreign keys, but that doesn't seem to be the case here, as the type of "ParentFolder" is "Folder".</p>
  
  <p>The folder type is set to auto-increment in the database, and has the attribute:</p>
  
  <pre><code>[DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
  </code></pre>
  
  <p>The underlying entity structure:</p>
  
  <pre><code>class Folder
  {
      #region database fields
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int FolderID { get; set; }
      public string Name { get; set; }
      public string Subtitle { get; set; }
      [ForeignKey("FolderID")]
      public Folder ParentFolder { get; set; }
      public bool IsHidden { get; set; }
      public bool IsSimple { get; set; }
      public string QueryOrFilePath { get; set; }
      #endregion
  }
  </code></pre>
  
  <p>And the SQL query to create the table:</p>
  
  <pre><code>CREATE TABLE IF NOT EXISTS Folders 
  (
      FolderID INTEGER PRIMARY KEY AUTOINCREMENT,
      Name varchar(255) NOT NULL,
      Subtitle varchar(255) NULL,
      ParentFolderID INT NULL,
      IsHidden BIT NOT NULL,
      IsSimple BIT NOT NULL,
      QueryOrFilePath varchar(255) NOT NULL,
      FOREIGN KEY (ParentFolderID) REFERENCES Folders(FolderID)
  );
  </code></pre>