title: Update One-to-Many entities when using independent associations in a detached scenario
body: <p>I'm a novice in using Entity Framework 6 and I got stuck trying to update an entity. I'm using the Code First approach and my model, reduced to the classes in question, looks like this:</p>
  
  <pre><code>public class Document
  {
      public long Key { get; set; }
      public string Name { get; set; }
  }
  
  public class Batch
  {
      public long Key { get; set; }
      public virtual List&lt;Document&gt; Documents { get; private set; }
  
      public void Add(Document document)
      {
          Documents.Add(document);
      }
  
      public void Remove(Document document)
      {
          Documents.RemoveAt(Documents.FindIndex(d =&gt; d.Key == document.Key));
      }
  }
  </code></pre>
  
  <p>There is a one to many relationship between the Batch and Document, modeled through independent associations, so there is no explicit FK. <strong>An important particularity is that the Document class doesn't know about the Batch.</strong> This is a difference from other similar questions on Stackoverflow, like <a href="https://stackoverflow.com/questions/6972178/entity-framework-code-first-update-one-to-many-relationship-with-independent">this one</a> for instance. Entity Framework generates a null-able column Batch_Key in the Document table. </p>
  
  <p>Here is the context class:</p>
  
  <pre><code>public class MyDbContext : DbContext
  {
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Entity&lt;Document&gt;().HasKey(d =&gt; d.Key);
          modelBuilder.Entity&lt;Batch&gt;().HasKey(b =&gt; b.Key);
  
          modelBuilder.Entity&lt;Batch&gt;().HasMany(b =&gt; b.Documents).WithOptional().WillCascadeOnDelete(false);
          base.OnModelCreating(modelBuilder);
      }
  }
  </code></pre>
  
  <p>I have a BatchRepository class with an Update() method that receives a Batch parameter and updates the batch in the database:</p>
  
  <pre><code>public class BatchRepository
  {
      public void Update(Batch item)
      {
          using (var dbCtx = new MyDbContext(DBContextName))
          {
              batchesContext.Batches.Attach(item);
              batchesContext.Entry(item).State = EntityState.Modified;
              batchesContext.SaveChanges();
          }
      }
  }
  </code></pre>
  
  <p>Here is a unittest for removing a document from a batch, that uses the Update() method:</p>
  
  <pre><code>[TestMethod]
  public void CheckRemoveDocument()
  {
      var batches = BatchRepository.FindAll().ToList();
      var batch = batches[0];
      var batchKey = batches[0].Key;
      var doc = batch.Documents[0];
      int batchNumberOfDocuments = batch.Documents.Count;
  
      batch.Remove(doc);
      BatchRepository.Update(batch);
  
      batch = BatchRepository.FindBy(batchKey);
      Assert.AreEqual(batchNumberOfDocuments - 1, batch.Documents.Count);
  }
  </code></pre>
  
  <p>The test fails, the batchNumberOfDocuments is the same as before. If I implement a method to remove all the documents from a batch, like this:</p>
  
  <pre><code>public class BatchRepository
  {
      public void RemoveDocuments(Batch item)
      {
          using (var dbCtx = new MyDbContext(DBContextName))
          {
              var existingBatch = batchesContext.Batches.Find(item.Key);
              batchesContext.Entry(existingBatch).Collection(b =&gt; b.Documents).Load();
              existingBatch.Documents.RemoveAll(d =&gt; true);
              batchesContext.SaveChanges();
          }
      }
  }
  </code></pre>
  
  <p>the following test succeeds:</p>
  
  <pre><code>[TestMethod]
  public void CheckRemoveAllDocuments()
  {
      var batches = BatchRepository.FindAll().ToList();
      var batch = batches[0];
      var batchKey = batches[0].Key;
      BatchRepository.RemoveDocuments(batch);
  
      batch = BatchRepository.FindBy(batchKey);
      Assert.AreEqual(0, batch.Documents.Count);
  }
  </code></pre>
  
  <p>So EF correctly tracks the relationship between the batch and the documents, setting the Batch_Key column to NULL for the documents removed. Why does this work in this scenario, but not in the one where I am updating? I assume this is because the Document entities linked to the batch are not attached to the context. The problem is that I don't know if the batch from the parameter of the Update() method has more documents, less documents, or an entirely different list of documents (also, it might be the case that something else than the Document list changed).</p>
  
  <p>An implementation like this:</p>
  
  <pre><code>public class BatchRepository
  {
      public void Update(Batch item)
      {
          using (var dbCtx = new MyDbContext(DBContextName))
          {
                  var existingBatch = batchesContext.Batches.Find(item.Key);
                  batchesContext.Entry(existingBatch).Collection(b =&gt; b.Documents).Load();
  
                  foreach (var doc in item.Documents)
                  {
                      batchesContext.Documents.Attach(doc);
                      batchesContext.Entry(doc).State = EntityState.Modified;
                  }
                  batchesContext.SaveChanges();
          }
      }
  }
  </code></pre>
  
  <p>throws an exception:</p>
  
  <blockquote>
    <p>System.InvalidOperationException: Attaching an entity of type
    'Document' failed because another entity of the same type already has
    the same primary key value. This can happen when using the 'Attach'
    method or setting the state of an entity to 'Unchanged' or 'Modified'
    if any entities in the graph have conflicting key values. This may be
    because some entities are new and have not yet received
    database-generated key values. In this case use the 'Add' method or
    the 'Added' entity state to track the graph and then set the state of
    non-new entities to 'Unchanged' or 'Modified' as appropriate.</p>
  </blockquote>
  
  <p>How should the Update() method be implemented to perform the update properly?</p>
  
  <p>Thank you and sorry if the question sounds confusing, it's all due to the confusion in my mind related to EF.</p>