I am new to ASP.NET Core. When I created a project with ASP.NET Identity enabled, there was an ApplicationDbContext
template automatically created for me.
public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
{
public ApplicationDbContext(
DbContextOptions options,
IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
{
}
}
Now, I also want ApplicationDbContext
automatically creates tables for my own data models.
public class Student
{
public int Id {get;set;}
public string name { get; set; }
}
Should I do something like this? But this is not working for me.
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");
}
}
Or should I create another DbContext
to work with my own custom data models?
CodePudding user response:
First, don't forget to use {get;set;}
public DbSet<Student> Students { get; set; }
Then you need to run this line into your package manager console
add-migration addStudentsTable
It will create this migration for you
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");
}
Then run this line also to update the database
update-database