title: Update Record with Composite Key - Entity Framework Core
body: <p>I am having an issue updating a record with a composite key using EF Core 5 and Net Core 5. I am able to get the record using both parts of the composite key (two ids in my case) but when I save the changes to the database I get the following error:</p>
  <p>Database operation expected to affect 1 row(s) but actually affected 24 row(s). Data may have been modified or deleted since entities were loaded. See <a href="http://go.microsoft.com/fwlink/?LinkId=527962" rel="nofollow noreferrer">http://go.microsoft.com/fwlink/?LinkId=527962</a> for information on understanding and handling optimistic concurrency exceptions.</p>
  <p>After looking in the database, it looks like entity framework is trying to update all the records in the table with same id (first part of the composite key) instead of updating the record that I got.</p>
  <p>Has anyone else seen this behavior? Any ideas of how to get around it or what I might be doing wrong?</p>
  <p>Here is a basic version of the table set up</p>
  <p>Table1:</p>
  <pre><code>Id (PK)
  </code></pre>
  <p>Table2:</p>
  <pre><code>Id (PK),  
  Table1Id (PK, FK)
  </code></pre>
  <p>Scenario where it fails:</p>
  <p>Table1:</p>
  <pre><code>Id  
  --
  1  
  2  
  </code></pre>
  <p>Table2:</p>
  <pre><code>Id, Table1Id  
  ------------
  1, 1  
  2, 1  
  1, 2  
  2, 2  
  </code></pre>
  <p>If I try to update the first record in Table2 (1, 1), EF would try to update it and the third record (1, 2) and throw the above error.</p>
  <p>Code:</p>
  <pre><code>// Getting record    
  var record = await context.Table2s
                            .FirstOrDefaultAsync(e =&gt; e.Id == 1 &amp;&amp; e.Table1Id == 1, cancellationToken);
  
  // Saving
  await context.SaveChangesAsync(cancellationToken);
  
  // I have also tried specifying which record to update before saving
  context.Table2s.Update(record);
  </code></pre>
  <p>Configuration for Table2:</p>
  <pre><code>builder.ToTable(&quot;Table2&quot;);
  builder.HasKey(e =&gt; new { e.Id, e.Table1Id });
  
  builder.HasOne(e =&gt; e.Table1)
                  .WithMany(m =&gt; m.Table2s)
                  .HasForeignKey(e =&gt; e.Table1Id)
                  .OnDelete(DeleteBehavior.Cascade);
  </code></pre>