title: Updating related entity in EF Core
body: <p>I am using Entity Framework Core with a code-first approach.  I hit this error when saving the changes to an entity which has a change to one of its related objects:</p>
  <blockquote>
  <p>&quot;The property 'BirdId' on entity type 'Bird' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key first delete the dependent and invoke 'SaveChanges' then associate the dependent with the new principal.&quot;</p>
  </blockquote>
  <p>I hit the error when I save the changes to an entity of type <code>Observation</code> with a updated to the related <code>Bird</code> object.  I have included the models setup below:</p>
  <pre><code>public class Observation
  {
      [Key]
      public int ObservationId { get; set; }
  
      // other properties...
  
      public int BirdId { get; set; }
  
      public Bird Bird { get; set; }
  }
  </code></pre>
  <p>The Bird class looks like this:</p>
  <pre><code>public class Bird
  {
      [Key]
      public int BirdId { get; set; }
  
      // other properties...
  
      public ICollection&lt;Observation&gt; Observations { get; set; }
  }
  </code></pre>
  <p>I have relied solely on the EF Core model conventions (I've not added code in the <code>OnModelCreating</code> method) which, from the EF migration, sets up the database like so:</p>
  <pre><code>        migrationBuilder.CreateTable(
              name: &quot;Observation&quot;,
              columns: table =&gt; new
              {
                  ObservationId = table.Column&lt;int&gt;(nullable: false)
                      .Annotation(&quot;SqlServer:Identity&quot;, &quot;1, 1&quot;),
                  BirdId = table.Column&lt;int&gt;(nullable: false),
              },
              constraints: table =&gt;
              {
                  table.PrimaryKey(&quot;PK_Observation&quot;, x =&gt; x.ObservationId);
                  table.ForeignKey(
                      name: &quot;FK_Observation_Bird_BirdId&quot;,
                      column: x =&gt; x.BirdId,
                      principalTable: &quot;Bird&quot;,
                      principalColumn: &quot;BirdId&quot;,
                      onDelete: ReferentialAction.Cascade);
              });
  </code></pre>
  <p><strong>Have I setup the model correctly?</strong></p>
  <p>My code for saving the updated Observation looks like this:</p>
  <pre><code>            observation.BirdId = model.Bird.BirdId;
              var bird = await _birdRepository.GetBirdAsync(model.Bird.BirdId);
              observation.Bird = bird;
  
              observation.LastUpdateDate = _systemClock.GetNow;
  
              await _unitOfWork.CompleteAsync();
  </code></pre>
  <p>However, I think the problem lies in the way the relationship is setup in the models.  Can anyone shed any light on the problem?</p>