title: Auto Increment ID in ASP.NET MVC
body: <p>I am trying to add a record to a table and have the primary key be auto generated. I have the <code>StudentID</code> column as primary key, <code>int, not null</code> in SQL Server. I keep getting this error:</p>
  
  <blockquote>
    <p>SqlException: Cannot insert the value NULL into column 'Student ID', table 'SchoolManagement.dbo.Student'; column does not allow nulls. INSERT fails.
    The statement has been terminated.</p>
  </blockquote>
  
  <p>Model (Student.CS):</p>
  
  <pre><code>namespace SchoolChallenge.Models
  {
      public partial class Student
      {
          [Key]
          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
          public int StudentId { get; set; }
          public string StudentNumber { get; set; }
          [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
          public string FirstName { get; set; }
          [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
          public string LastName { get; set; }
          [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
          public string HasScholarship { get; set; }
      }
  }
  </code></pre>
  
  <p>Controller (<code>StudentsController</code>):</p>
  
  <pre><code>// POST: Students/Create
  [HttpPost]
  [ValidateAntiForgeryToken]
  public async Task&lt;IActionResult&gt; Create([Bind("StudentId,StudentNumber,FirstName,LastName,HasScholarship")] Student student)
  {
      if (ModelState.IsValid)
      {
          _context.Add(student);
          await _context.SaveChangesAsync();
          return RedirectToAction(nameof(Index));
      }
  
      return View(student);
  }
  </code></pre>
  
  <p>SchoolManagementContext.cs:</p>
  
  <pre><code>modelBuilder.Entity&lt;Student&gt;(entity =&gt;
  {
      entity.Property(e =&gt; e.StudentId)
          .HasColumnName("Student ID")
          .ValueGeneratedOnAdd();
  
      entity.Property(e =&gt; e.FirstName)
          .IsRequired()
          .HasColumnName("First Name")
          .HasMaxLength(50);
  
      entity.Property(e =&gt; e.HasScholarship)
          .IsRequired()
          .HasColumnName("Has Scholarship")
          .HasColumnType("nchar(10)");
  
      entity.Property(e =&gt; e.LastName)
          .IsRequired()
          .HasColumnName("Last Name")
          .HasMaxLength(50);
  
      entity.Property(e =&gt; e.StudentNumber).HasColumnName("Student Number");
  });
  </code></pre>