【问题标题】:How to create tables for roles and users automatically using identity framework with code first approach in asp.net mvc 5如何在 asp.net mvc 5 中使用身份框架和代码优先方法自动为角色和用户创建表
【发布时间】:2020-03-05 22:28:09
【问题描述】:

我正在创建一个应用程序并创建了两个表,但想通过代码优先的方法创建 AspNetRoles、AspNetUsers、AspNetUsersRoles 等表。如果不使用 DB first 方法或手动制作表格,它将如何创建

 public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        createRolesandUsers();
    }
    private void createRolesandUsers()
    {
        ApplicationDbContext context = new ApplicationDbContext();

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
        var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));


        // In Startup iam creating first Admin Role and creating a default Admin User    
        if (!roleManager.RoleExists("SuperAdmin"))
        {

            // first we create Admin rool   
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            role.Name = "SuperAdmin";
            roleManager.Create(role);

            //Here we create a Admin super user who will maintain the website                  

            var user = new ApplicationUser();
            user.UserName = "abc";
            user.Email = "abc@gmail.com";

            string userPWD = "password";

            var chkUser = UserManager.Create(user, userPWD);

            //Add default User to Role Admin   
            if (chkUser.Succeeded)
            {
                var result1 = UserManager.AddToRole(user.Id, "SuperAdmin");

            }
        }

        //creating Creating Manager role
        if (!roleManager.RoleExists("Manager"))
        {
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            role.Name = "Manager";
            roleManager.Create(role);

        }

        // creating Creating Employee role    
        if (!roleManager.RoleExists("Employee"))
        {
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            role.Name = "Employee";
            roleManager.Create(role);

        }
    }

我做过这样的事情,没有做过其他事情

【问题讨论】:

    标签: asp.net asp.net-mvc-5 asp.net-identity


    【解决方案1】:

    如果我的问题正确,您只需要扩展 IdentityDbContext 它是身份框架的一部分并生成迁移。这是一种执行代码优先的方法。 https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli

    【讨论】:

    • 我不使用核心。简单的 asp.net mvc 5
    • 要为“RealTimeNotificationSystem.Models.RealTimeContext”启用迁移,请使用 Enable-Migrations -ContextTypeName RealTimeNotificationSystem.Models.RealTimeContext。这里-ContextTypeName是什么意思?
    • 我已经完成了数据库但没有进行迁移,因此项目中没有迁移文件夹。数据库的迁移历史虽然已更新
    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多