title: EF Core - Cannot insert explicit value for identity column SqlException
body: <p>In my app I am using EF Core to define 2 entities (Code First), <code>Meeting</code> and <code>PostcodeDetail</code> defined as follows:</p>
  
  <pre><code>public class Meeting
  {
    public int Id { get; set;}
    public PostcodeDetail PostcodeDetail { get; set; }
  
    // other properties removed for brevity
  }
  
  public class PostcodeDetail
  {
    public int Id { get; set; }
    public ICollection&lt;Meeting&gt; Meetings { get; set; } = new List&lt;Meeting&gt;();
  
    // other properties removed for brevity
  }
  </code></pre>
  
  <p>When I create a new <code>Meeting</code> and try assigning an existing <code>PostcodeDetail</code> entity as follows:</p>
  
  <pre><code>var meeting = new Meeting();
  var details = context.PostcodeDetails
                          .SingleOrDefault(i =&gt; i.Prefix == prefix);
  
  meeting.PostcodeDetail = details;
  context.SaveChanges();
  </code></pre>
  
  <p>I get this exception:</p>
  
  <blockquote>
    <p>Microsoft.EntityFrameworkCore.DbUpdateException: SqlException: Cannot insert explicit value for identity column in the table 'PostcodeDetail' when IDENTITY_INSERT is set to OFF</p>
  </blockquote>
  
  <p>I can't see why an insert statement is executing on <code>PostcodeDetail</code>, as I am retrieving an exisiting entity from the database - can anyone see what I'm doing wrong here?</p>
  
  <p><strong>Edit:</strong> When I run SQL Server Profiler I can see the following is executed</p>
  
  <blockquote>
    <p>INSERT INTO [PostcodeDetail] ([Id], [DateCreated], [DateModified], [District], [Prefix], [Region])
    VALUES (@p0, @p1, @p2, @p3, @p4, @p5);
    ',N'@p0 int,@p1 datetime2(7),@p2 datetime2(7),@p3 nvarchar(4000),@p4 nvarchar(4000),@p5 nvarchar(4000)',@p0=113,@p1='2019-01-02 15:50:49.5874691',@p2='2019-01-02 15:50:49.5874640',@p3=N'Guernsey',@p4=N'GY',@p5=N'Channel Islands'</p>
  </blockquote>
  
  <p>I don't know why an insert is generated, as I am getting the PostcodeDetail from the database and referencing it on the new <code>Meeting</code></p>