【问题标题】:Create role using entity framework core migrations使用实体框架核心迁移创建角色
【发布时间】:2017-09-18 20:35:16
【问题描述】:

我正在使用 EF Core (2.0.0) 创建我的第四个迁移脚本。在那里我想向数据库添加一些角色。

问题是,我不确定如何执行此操作。目前我有这个:

protected override void Up(MigrationBuilder migrationBuilder)
{
    // todo: Pass connection string somehow..?
    var opt = new DbContextOptions<ApplicationContext>();
    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationContext(opt)));

    //if (!roleManager.RoleExists("ROLE NAME"))
    //{
        // todo: create the role...
    //}
}

但是像这样创建RoleManager 会给我以下错误:

没有给出与所需形式相对应的参数 参数'roleValidators' 'RoleManager.RoleManager(IRoleStore, IEnumerable>,ILookupNormalizer, IdentityErrorDescriber, ILogger>)'

我不知道如何解决这个问题。我找不到任何有关如何在 .NET Core 中使用迁移正确执行此操作的信息。

我在这段代码中面临两个问题:

  • 我正在尝试以某种方式创建 DbContext 的实例。我不应该能够从我的迁移代码中获取 DbContext 吗?
  • 像这样实例化RoleManager 不起作用,需要解决。

我该如何解决这些问题?

【问题讨论】:

    标签: asp.net-core entity-framework-core entity-framework-migrations


    【解决方案1】:

    Up 方法基本上是一个指令文件,告诉 EF 的数据库迁移器如何生成数据库升级脚本。该方法在脚本生成时执行。在那里进行任何数据操作是绝对不合适的。 EF 核心尚不支持播种,因此您必须在应用程序启动时添加缺失的角色,例如通过this 之类的内容。

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 1970-01-01
      • 2021-06-27
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 2017-04-06
      • 2019-11-08
      相关资源
      最近更新 更多