Create role using entity framework core migrations

asp.net-core ef-migrations entity-framework-core

Question

I'm creating my 4th migrations script with EF Core (2.0.0). In there I want to add a few roles to the database.

The problem is, is that I'm not really sure how to do this. Currently I have this:

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...
    //}
}

But creating the RoleManager like that gives me the following error:

There is no argument given that corresponds to the required formal parameter 'roleValidators' of 'RoleManager.RoleManager(IRoleStore, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, ILogger>)'

I'm not sure how to solve this problem. I couldn't find any info on how to do this properly in .NET Core using migrations.

I'm facing two issues in this code:

  • I'm trying to create an instance of the DbContext somehow. Shouldn't I be able to get the DbContext from within my migrations code?
  • Instantiating the RoleManager like this doesn't work and needs to be resolved.

How can I solve these problems?

1
2
9/15/2017 9:09:26 PM

Accepted Answer

The Up method is basically an instruction file that tells EF's database migrator how to generate a database upgrade script. The method is executed when the script is generated. Doing any data manipulation there is absolutely out of place. EF core doesn't support seeding yet, so you have to add missing roles when the application starts, for example by something like this.

0
9/18/2017 12:35:16 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow