如何向EntityFramework Core添加角色?

时间:2016-08-12 17:37:14

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

我使用"个人用户帐户启动了一个新的asp.net核心Web应用程序"授权模板。似乎EF的所有配置都发生在Startup.cs

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

但是我找不到任何关于如何添加一个的例子或文档。

1 个答案:

答案 0 :(得分:0)

我以这种方式实现了这一目标。我在DBContext类的扩展类中创建了一个种子方法,并在启动类的configure方法中调用它。

 public static class CrmContextExtension
{
    public static async Task SeedDataForContext(this CrmContext context)
    {
        // if there is no role exist then create some default role 'administrator' 
        var logger = LogManager.GetCurrentClassLogger();

        if (context.Roles.Count() == 0)
        {
            var store = new RoleStore<IdentityRole>(context);
            var manager = new RoleManager<IdentityRole>(store,null, null, null, null,null);
            var role = new IdentityRole { Name = "administrator" }; 
            IdentityResult result = await manager.CreateAsync(role); 
            logger.Info(result.Succeeded ? "Role 'administrator' has been successfully created" : 
                "Couldn't create role 'administrator' in the seed.");
        } 
    }
}

 public async void Configure(IApplicationBuilder app, IHostingEnvironment env, 
        ILoggerFactory loggerFactory, CrmContext context)
    { ...... 
      await context.SeedDataForContext();
      app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
     }

尝试一下,如果您遇到任何问题,请告诉我。