title: Entity Framework Improperly tracking many-to-many relationship
body: <h2>Setup</h2>
  
  <p>consider the following data tables:</p>
  
  <pre><code>*Files*
  | PK_File_ID | Name |
  
  
  *FileStatusLog*
  | (Key) FK_File_ID | (Key) FK_Status_ID | (Key) Date |
  
  *FileStatus*
  | PK_Status_ID | Name |
  </code></pre>
  
  <p>The above table is represented by the following Code First objects:</p>
  
  <pre><code>public class File
  {
      [Key]
      public int Id{ get; set; }
      public string Name {get;set}
  
      public virtual List&lt;FileStatusLog&gt;
  }
  
  public class FileStatusLog
  {
      [Column(Order = 0), Key, ForeignKey("File")]
      public int Fk_File_Id { get; set; }
      [Column(Order = 1), Key, ForeignKey("Status")]
      public int Fk_Status_Id { get; set; }
      [Column(Order = 2), Key]
      public DateTime Date { get; set; }
      public virtual File File { get; set; }
      public virtual FileStatus Status { get; set; }
  }
  
  public class FileStatus
  {
      [Key]
      public int Id{ get; set; }
      public string Name { get; set; }
      public virtual List&lt;FileStatusLog&gt; StatusEntries { get; set; }
  }
  </code></pre>
  
  <h2>Problem</h2>
  
  <p>My problem arises when inserting a disconnected file.  I realize that this is the beloved task of inserting a disconnected Object Graph in Entity Framework, still a painful ordeal, but I have been able to do it before.  I suppose it is the Many-To-Many relationship that is throwing me off.</p>
  
  <p>If I don't do anything to the file, and just Insert it, it tries to add a duplicate copy of <code>FileStatus</code>.  This is an expected Side Effect of inserting disconnected Object Graphs.  The Work around is to make sure that each <code>FileStatus</code> is mapped to the Data Context:</p>
  
  <pre><code>public File Insert(File FileToInsert)
  {
      for (int i = 0; i &lt; FileToInsert.FileStatusLog.Count; i++)
      {
          var Entry = context.Statuses.Find(FileToInsert.FileStatusLog[i].FileStatus.Id);
          if (Entry != null)
          {
              Entry = Mapper.Map(FileToInsert.FileStatusLog[i].FileStatus, Entry);
              FileStatusLog[i].FileStatus = Entry;
          }
      }
      context.Files.Add(FileToInsert);
      context.SaveChanges();
  }
  </code></pre>
  
  <p>The Problem is that the above code is not working as intended.  The Composite key table is only allowing 1 row per status. Whenever a new file is being inserted with a status that has been used before, that row in the <code>FileStatusLog</code> in being <em>overridden</em> by the new <code>File</code> Data.  How would I be getting this result?  Doing nothing, it tries to duplicate Statuses in the <code>FileStatus</code> table. Try to bind those Statuses, and it won't et you insert Duplicate <code>Status_Id</code>'s in the Join Table.</p>
  
  <p>Any Ideas as to what is going on here?</p>