Reputation: 81
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");
});
Upvotes: 3
Views: 35699
Reputation: 9
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)
Upvotes: -1
Reputation: 81
I changed the Identity
of my primary key from No
to Yes
in SQL Server, and now it auto increments and no error is displayed.
Upvotes: 1
Reputation: 392
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
Upvotes: 6