我有一个关于在ASP.NET Core MVC应用程序中创建新表的问题。我用"个人用户帐户"创建了它。所以我在DB中有身份表。
如何在此数据库中创建自己的表?我应该创建一个新的数据库上下文吗?
例如:我想为学生和问题(及其答案)创建一个表格。
答案 0 :(得分:2)
由于您已经说过使用了Individual User Accounts
身份模板,因此您可以在其上添加自定义模型,例如:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
//....
}
public DbSet<Student> Students{ get; set; }
public DbSet<Question> Questions { get; set; }
public DbSet<Answer> Answers { get; set; }
//....
}
在新更改后添加/运行迁移 - 从“工具”菜单中找到Package Console Manager
下的Nuget Console Manager
。使用ApplicationDbContext选择项目并运行命令,如屏幕截图所示。
答案 1 :(得分:1)
创建模型:
假设您有以下型号:
public class Post{
public int Id {get; set;}
public string Name {get; set;}
}
,创建一个名为Persistence的文件夹(或者您可以随意调用它)
Inside Persistence文件夹中添加类似
的类public class MyDbContext : DbContext {
public DbSet<Post> Posts {get; set;}
public MyDbContext((DbContextOptions<MyDbContext> options)
: base (options)
{
}
}
现在在Startup.cs
中,将此行添加到ConfigureServices
函数:
services.AddDbContext<MyDbContext>(options => options.UseSqlServer("connStr"));
现在使用dotnet cli
dotnet ef migrations添加AddPostsTable --context MyDbContext
查看更多信息:docs here