テーブルにレコードを追加しようとしていて、プライマリキーを自動生成しようとしています。私は列をプライマリキーとしてint, not null
SQL Serverに持っています。ASP.NET MVCの自動インクリメントID
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; }
}
}
コントローラ(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");
});
'database first'か' code first'のどちらを使ったのですか? –
まずデータベース。私はMSSQLでアイデンティティを設定する必要がありますか? – Freiza1991
はい。あなたはそれをしたほうがいい。 –