简体   繁体   中英

Auto Increment ID in ASP.NET MVC

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

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

我在SQL Server中将主键的Identity从“ No更改为“ Yes ,现在它会自动递增,并且不会显示任何错误。

If you're using Visual Studio, you can edit the primary ID, by opening the table definition. Open the Server Explorer, right click on the table, and select "open table definition". Under the "Design" tab at the bottom, either add or edit the following:

CONSTRAINT [PK_dbo.TableName] PRIMARY KEY CLUSTERED ([ID] ASC)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM