Auto Increment ID in ASP.NET MVC

c# entity-framework sql-server

Question

I am trying to add a record to a table and have the primary key be auto generated. I have the StudentID column as primary key, int, not null in SQL Server. I keep getting this error:

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.

Model (Student.CS):

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; }
    }
}

Controller (StudentsController):

// POST: Students/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> 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);
}

SchoolManagementContext.cs:

modelBuilder.Entity<Student>(entity =>
{
    entity.Property(e => e.StudentId)
        .HasColumnName("Student ID")
        .ValueGeneratedOnAdd();

    entity.Property(e => e.FirstName)
        .IsRequired()
        .HasColumnName("First Name")
        .HasMaxLength(50);

    entity.Property(e => e.HasScholarship)
        .IsRequired()
        .HasColumnName("Has Scholarship")
        .HasColumnType("nchar(10)");

    entity.Property(e => e.LastName)
        .IsRequired()
        .HasColumnName("Last Name")
        .HasMaxLength(50);

    entity.Property(e => e.StudentNumber).HasColumnName("Student Number");
});
1
0
9/6/2017 4:48:29 AM

Popular Answer

If your code does not provide student ID then you must make it an identity field in your table.

Make sure the student ID field has this in the table design.

IDENTITY (1,1) 

This will automatically generate the student ID for you in the database on row insert and increment the ID by 1 for every new row.

I dont believe you can make a column identity after its made iirc. So either drop the table and recreate or drop the incorrect column and replace with the correct one.

So to drop a column and add a new one:

Alter TABLE dbo.t_name drop column studentID

Then:

Alter TABLE dbo.t_name add studentID int IDENTITY(1,1) NOT NULL
1
9/6/2017 3:14:00 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow