MVC5种子用户和角色 [英] MVC5 Seed Users and Roles

查看:190
本文介绍了MVC5种子用户和角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经玩关于新MVC5,我有几个模型,控制器和使用code首先迁移看待设置。

I have been playing about with the new MVC5, i have a few models, controller and views setup using code first migrations.

我的问题是我如何种子用户和卷?我目前在Configuration.cs我的种子播种方法有一定的参考的数据。但在我看来,用户和角色表没有创建,直到第一次的东西击中AccountsController。

My question is how do i seed users and rolls? I currently seed some reference data in my Seed method in Configuration.cs. But it looks to me that the user and roles tables are not created until something first hits the AccountsController.

我现在有两个连接字符串,所以我可以从我的认证分开我的数据到不同的数据库。

I currently have two connection strings so i can separate my data from my authentication into different databases.

我怎样才能获得用户,角色等填充表格连同我的人?而不是当账户控制器被击中?

How can i get the user, roles, etc tables populate along with my others? And not when the account controller is hit?

推荐答案

下面是例子平常种子办法:

Here is example of usual Seed approach:

protected override void Seed(SecurityModule.DataContexts.IdentityDb context)
{
    if (!context.Roles.Any(r => r.Name == "AppAdmin"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "AppAdmin" };

        manager.Create(role);
    }

    if (!context.Users.Any(u => u.UserName == "founder"))
    {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser {UserName = "founder"};

        manager.Create(user, "ChangeItAsap!");
        manager.AddToRole(user.Id, "AppAdmin");
    }
}

我用包管理器更新数据库。 DB和所有表创建和数据播种。

I used package-manager "update-database". DB and all tables were created and seeded with data.

这篇关于MVC5种子用户和角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆