ASP.NET 核心 ApiAuthorizationDbContext 没有为数据模型创建 table

ASP.NET Core ApiAuthorizationDbContext not creating table for data model

我是 ASP.NET Core 的新手。当我创建一个启用了 ASP.NET Identity 的项目时,系统会自动为我创建一个 ApplicationDbContext 模板。

public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
{
    public ApplicationDbContext(
        DbContextOptions options,
        IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
    {
    } 
}

现在,我还希望ApplicationDbContext自动为我自己的数据模型创建表。

public class Student
{
    public int Id {get;set;}
    public string name { get; set; }
}

我应该这样做吗?但这对我不起作用。

public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
{
    public ApplicationDbContext(
        DbContextOptions options,
        IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
    {
    }

    public DbSet<Student> students;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Student>().ToTable("Student");
    }
}

或者我应该创建另一个 DbContext 来使用我自己的自定义数据模型吗?

首先,别忘了使用{get;set;}

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

然后你需要运行这一行到你的package manager console

add-migration addStudentsTable

它将为您创建此迁移

protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Students",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    name = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Students", x => x.Id);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Students");
        }

然后运行这一行也更新数据库

update-database