【问题标题】:How do you add a Role to EntityFramework Core?如何向 EntityFramework Core 添加角色?
【发布时间】:2016-12-19 19:15:11
【问题描述】:
我已经使用“个人用户帐户”模板启动了一个新的 asp.net 核心 Web 应用程序进行授权。看来EF的所有配置都发生在Startup.cs中
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
但我找不到任何示例或有关如何添加示例的文档。
【问题讨论】:
标签:
asp.net-identity
entity-framework-core
【解决方案1】:
我是通过这种方式实现的。我在 DBContext 类的扩展类中创建了一个种子方法,并在启动类的配置方法中调用它。
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?}");
});
}
试试这个,如果您遇到任何问题,请告诉我。