Jannik
Jannik

Reputation: 2439

Seed roles in an ASP.NET MVC Core project with Entity Framework

I am trying to seed some roles to my identity db context, when I initially create the database.

For that I tried to implement the code like it was stated here: https://stackoverflow.com/a/29547994/985798

I tried this in the ConfigureServices-method inside my Startup-class: public void ConfigureServices(IServiceCollection services)

using this snippet:

var rolestore =
    new Microsoft.AspNetCore.Identity.EntityFrameworkCore.
        RoleStore<Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole>(identityContext);

var roleManager = new Microsoft.AspNetCore.Identity.RoleManager
                  <Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole>(rolestore);

//use rolemanager to insert roles etc.

The problem is, that it seems to not work in an fresh Core-project, created with Visual Studio 2017.

It gives me the following build error:

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

Even if I use the other overload (with null values for the other parameters), the RoleManager seems to have no "Create" method anymore.

So, I am stuck at this point. What do I need to do? Has something changed in the ASP.NET MVC Core implementation of the rolemanager? Do I use something wrong?

Upvotes: 2

Views: 3283

Answers (1)

mvermef
mvermef

Reputation: 3924

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

public static class Seed
{
    public static void Initialize(IServiceProvider provider)
    {
        var _context = provider.GetRequiredService<ApplicationDbContext>();
        var userManager = provider.GetRequiredService<UserManager<ApplicationUser>>();
        var roleManager = provider.GetRequiredService<RoleManager<IdentityRole>>();


    }
}

Then below the majority of the code in the in the Configure() in startup.cs

Seed.Initialize(app.ApplicationServices);

HTH (hope that helps).

Upvotes: 4

Related Questions