简体   繁体   English

ASP.NET MVC中的自动递增ID

[英]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.我将StudentID列作为主键, int, not null SQL 服务器中的 null。 I keep getting this error:我不断收到此错误:

SqlException: Cannot insert the value NULL into column 'Student ID', table 'SchoolManagement.dbo.Student'; SqlException:无法将值 NULL 插入“学生 ID”列、表“SchoolManagement.dbo.Student”; column does not allow nulls.列不允许空值。 INSERT fails.插入失败。 The statement has been terminated.该语句已终止。

Model (Student.CS): Model(学生.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 ): 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:学校管理上下文.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. 这将在插入行时自动在数据库中为您生成学生ID,并为每个新行将ID递增1。

I dont believe you can make a column identity after its made iirc. 我不相信您可以在完成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.如果您使用的是 Visual Studio,则可以通过打开表定义来编辑主要 ID。 Open the Server Explorer, right click on the table, and select "open table definition".打开Server Explorer,右击表,select“打开表定义”。 Under the "Design" tab at the bottom, either add or edit the following:在底部的“设计”选项卡下,添加或编辑以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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