title: How can we create a new record with EF when the Primary Key / Identity column is null?
body: <p>We are using Entity Framework 5 to create a new Answer record in our SQL Server 2012 database.</p>
  
  <p>Here's the Answer Class:</p>
  
  <pre><code>public class Answer
  {
      public int? AnswerId { get; set; }
      public string Text { get; set; }
  
  }
  </code></pre>
  
  <p>The SQL:</p>
  
  <pre><code>CREATE TABLE Answer (
     [AnswerId] INT IDENTITY (1, 1) NOT NULL,
     ...
     ...
     CONSTRAINT [PK_Answer] PRIMARY KEY CLUSTERED ([AnswerId] ASC)
  </code></pre>
  
  <p>Here is the EF Mapping:</p>
  
  <pre><code>public class AnswerMap : EntityTypeConfiguration&lt;Answer&gt;
  {
      public AnswerMap()
      {
          // Primary Key
          this.HasKey(t =&gt; t.AnswerId);
  
          // Identity
          this.Property(t =&gt; t.AnswerId)
              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  
      }
  }
  </code></pre>
  
  <p>However when a new Answer is inserted with a null in the AnswerId we still get the following:</p>
  
  <p>The key field 'AnswerId' cannot have a value of null. 
  A non-null value is required for the key fields defined on type 'Answer'.</p>
  
  <pre><code>System.InvalidOperationException was unhandled by user code
    HResult=-2146233079
    Message=The key field 'AnswerId' cannot have a value of null. A non-null value is required for the key fields defined on type 'Answer'.
    Source=System.Data.Entity
    StackTrace:
         at System.Data.Objects.ObjectStateManager.CreateEntityKey(EntitySet entitySet, Object entity)
         at System.Data.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet, String argumentName)
         at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
         at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
         at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
         ....
  </code></pre>
  
  <p>So how can I add my POCO class. The only thing I can do is set AnswerId to null as it's a database generated number. But then when I do that EF complains it's null even though I specified it's an identity column to EF. </p>