使用Identity将新表添加到ASP .NET Core MVC应用程序中

时间:2018-04-16 11:59:33

标签: c# database asp.net-core asp.net-identity

我有一个关于在ASP.NET Core MVC应用程序中创建新表的问题。我用"个人用户帐户"创建了它。所以我在DB中有身份表。

如何在此数据库中创建自己的表?我应该创建一个新的数据库上下文吗?

例如:我想为学生和问题(及其答案)创建一个表格。

2 个答案:

答案 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选择项目并运行命令,如屏幕截图所示。

enter image description here

答案 1 :(得分:1)

  1. 创建模型

    假设您有以下型号:

    public class Post{
    
      public int Id {get; set;}
      public string Name {get; set;}
    
    }
    
  2. 根目录中的
  3. ,创建一个名为Persistence的文件夹(或者您可以随意调用它)

  4. Inside Persistence文件夹中添加类似

    的类
    public class MyDbContext : DbContext {
    
        public DbSet<Post> Posts {get; set;}
        public MyDbContext((DbContextOptions<MyDbContext> options)
         : base (options)
        {
    
        }
    }
    
  5. 现在在Startup.cs中,将此行添加到ConfigureServices函数

    services.AddDbContext<MyDbContext>(options => options.UseSqlServer("connStr"));

  6. 现在使用dotnet cli

  7. 创建首次迁移的时间
      

    dotnet ef migrations添加AddPostsTable --context MyDbContext

    查看更多信息:docs here