实体“学生”需要定义主键

时间:2019-12-25 11:15:10

标签: c# asp.net-core

在为Student控制器创建视图时遇到了这个问题,我正在使用SQL Server和Visual Studio 2019。

我正在使用这些依赖项

  • Microsoft.CodeAnalysis.Razor版本= 2.1.1
  • Microsoft.EntityFrameworkCore Version = 2.1.1“
  • Microsoft.EntityFrameworkCore.SqlServer版本= 2.1.1
  • Microsoft.EntityFrameworkCore.Tools Version = 2.1.1

=== Student.CS ===

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace ASP_Core_EF.Models
{
    public enum Status { UnderGraduate, PostGraduate, Masters, Phd, Suspended }

    public class Student
    {
        [Key]
        public int StudentId { get; }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        [DataType(DataType.Date)]
        public DateTime DOB { get; set; }
        [DataType(DataType.Date)]
        public DateTime RegistrationDate { get; set; }

        public int GenderId { get; set; }
        public Status? Status { get; set; }
    }
}

=== DB_Context.CS ===

using ASP_Core_EF.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ASP_Core_EF.Repository
{
    public class DB_Context : DbContext
    {
        public DB_Context(DbContextOptions<DB_Context> options ) : base(options) { }

        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }

        public DbSet<Gender> Gender { get; set; }

        public DbSet<Enrollment> Enrollments { get; set; }
   }

}

1 个答案:

答案 0 :(得分:1)

您缺少set属性,因此出现错误

[Key]
public int StudentId { get; set;}

[Key]
public int StudentId { get; private set;}