title: Entity Framework Code First Migrations: Set Primary Key Value
body: <p>I have a table that stores some extra data for some rows of a table like:</p>
  
  <pre><code>public class QuoteExtra
  {
      [Key]
      public int QuoteId { get; set; }
      // More fields here
  }
  </code></pre>
  
  <p>I'd like to be able to add rows to this table where I explicitly set the PK.</p>
  
  <p>If I simply leave it as above, setting a value and submitting the row causes the value to be discarded and replaced with the auto-generated value from the database (and the column is defined as an Identity column in the actual schema).</p>
  
  <p>This appears to be the right solution:</p>
  
  <pre><code>public class QuoteExtra
  {
      [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.None)]
      public int QuoteId { get; set; }
      // More fields here
  }
  </code></pre>
  
  <p>However this instead gets me the exception:</p>
  
  <blockquote>
    <p>Cannot insert explicit value for identity column in table 'EnumTest' when IDENTITY_INSERT is set to OFF.</p>
  </blockquote>
  
  <p>So, how do I write my class so that I'm able to set the value of a Primary Key in EF?</p>
  
  <p>Edit:</p>
  
  <p>I tried adding the following Code-based Migration to set IDENTITY_INSERT to ON:</p>
  
  <pre><code>public override void Up()
  {
      Sql("SET IDENTITY_INSERT QuoteExtra ON");
  }
  </code></pre>
  
  <p>I ran it and tried again, but got the same exception as above. What's strange is the database does reflect this setting, and running SQL against it directly does allow me to insert arbitrary values in for the primary key - so it would appear Entity Framework itself is enforcing this rule, and neglecting to recognize that IDENTITY_INSERT is not in fact set to off. Do I need to set it somewhere in EF itself?</p>
  
  <p>Edit 2:</p>
  
  <p>I misunderstood IDENTITY_INSERT; I assumed setting it once left it on for that table indefinitely. In fact it lives as long as the "Session," meaning that for example setting it in a Migration means it lives... as long as that Migration runs, and has no bearing on future connections like my later .Add() with EF, which explains why I still got that exception - the DB really is the source of the exception, not EF. Since IDENTITY_INSERT is limited to at most one table per session it's a fairly inefficient way to do this - not creating an Identity PK column in the first place seems like a better route.</p>