c# - ASP.NET MVC 中的自动递增 ID

标签 c# sql-server entity-framework

我正在尝试向表中添加一条记录并自动生成主键。我在 SQL Server 中将 StudentID 列作为主键,int,not null。我不断收到此错误:

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.

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

最佳答案

如果您的代码不提供学生 ID,那么您必须将其作为表中的标识字段。

确保学生 ID 字段在表设计中有这个。

IDENTITY (1,1) 

这将在插入行时自动为您在数据库中生成学生 ID,并为每个新行将 ID 递增 1。

我不相信您可以在创建 iirc 之后创建列标识。因此,要么删除该表并重新创建,要么删除不正确的列并替换为正确的列。

所以要删除一列并添加一个新列:

Alter TABLE dbo.t_name drop column studentID

然后:

Alter TABLE dbo.t_name add studentID int IDENTITY(1,1) NOT NULL

关于c# - ASP.NET MVC 中的自动递增 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066005/

相关文章:

c# - 如何使用 C# 在 Nlog 中动态禁用特定日志?

sql-server - 登录 SSIS 的最佳方式

c# - Entity Framework 4.3 Windows Azure 关键字不受支持 : 'metadata'

c# - 具有多个参数的 Web API 路由

c# - 删除xml中的特定节点

c# - 日期字段中具有可为空值的存储过程

带有 LIKE 和 IN 的 SQLWhere 子句

c# - 使用 DI 添加 dbcontext 时是否需要调用 context.dispose?

c# - 手动将现有对象分配给 Entity Framework 导航属性

c# - 如何使用 Auto Mapper For 嵌套对象