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

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

问题描述

我一直在使用新的MVC 5,我有一些使用代码优先移植的模型,控制器和视图设置.

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

我的问题是如何播种用户和角色?我目前在Configuration.cs的Seed方法中植入了一些参考数据.但是在我看来,直到第一次击中AccountController才创建用户和角色表.

My question is how do I seed users and roles? 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 AccountController.

我目前有两个连接字符串,因此可以将身份验证中的数据分离到不同的数据库中.

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?

推荐答案

以下是常用的Seed方法的示例:

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");
    }
}

我使用了包管理器更新数据库".数据库和所有表均已创建并填充了数据.

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

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

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