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

查看:26
本文介绍了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?

推荐答案

以下是常用种子方法的示例:

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天全站免登陆