我是 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來使用我自己的自定義資料模型?
uj5u.com熱心網友回復:
首先,不要忘記使用 {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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371322.html
標籤:C# asp.net核心 asp.net-core-mvc
