【问题标题】:Code First Seed Asp.net IdentityCode First 种子 Asp.net 身份
【发布时间】:2016-05-05 06:29:16
【问题描述】:

我正在为一个已经运行了几个月的项目制定新要求。我正在使用带有 Asp.net Identity 的 Code First (EF6)。我需要在种子方法中添加一个新的用户角色并将这个角色附加到管理员。 如何在种子中向管理员添加新角色? 下面是我的种子方法的代码sn-p。

 protected override void Seed(myDbContext context)
    {
if (!context.Roles.Any())
        {
            var userManager =
                new UserManager<AppUser, Guid>(
                    new UserStore<AppUser, AppRole, Guid, AppUserLogin, AppUserRole, AppUserClaim>(context));
            var roleManager = new RoleManager<AppRole, Guid>(new RoleStore<AppRole, Guid, AppUserRole>(context));

            var adminRole = new AppRole() {Name = "admin"};
            roleManager.Create(adminRole);


            var admin = new Admin()
            {
                UserName = "test@test.com",
                EmailConfirmed = true,
                SecurityStamp = Guid.NewGuid().ToString()
            };
            admin.Roles.Add(new AppUserRole()
            {
                RoleId = adminRole.Id
            });


            userManager.Create(admin, "pwd");

            // user.Roles.Add(new IdentityUserRole { RoleId = userRole.Id, UserId = user.Id });

            base.Seed(context);
        }

    }

【问题讨论】:

    标签: ef-code-first asp.net-identity-2


    【解决方案1】:

    如果您有一个实时应用程序并已运行迁移,那么您的代码将无法运行,因为 !context.Roles.Any() 将是错误的,因为您现在拥有角色。要使您的脚本具有幂等性,请执行以下操作:

    protected override void Seed(myDbContext context)
    {
    
        var userManager = new UserManager<AppUser, Guid>(new UserStore<AppUser, AppRole, Guid, AppUserLogin, AppUserRole, AppUserClaim>(context));
        var roleManager = new RoleManager<AppRole, Guid>(new RoleStore<AppRole, Guid, AppUserRole>(context));
    
        // see if this role exists -- repeat for all roles
        if (!context.Roles.Any(r => r.Name == "admin"))
        {
            var adminRole = new AppRole() {Name = "admin"};
            roleManager.Create(adminRole);
        }
    
        // see if the user exists -- repeat for all users
        if (!context.Users.Any(u => u.UserName == "test@test.com")
        {
            var admin = new Admin()
            {
                UserName = "test@test.com",
                EmailConfirmed = true,
                SecurityStamp = Guid.NewGuid().ToString()
            };
            userManager.Create(admin, "pwd");
        }
    
        // see if the user has the role -- repeat for all roles for user, all users
        if (!userManager.IsInRole(admin.Id, "admin")
        {
             userManager.AddToRole(admin.Id, "admin")
        }
    
        ...
    
        base.Seed(context);
    
    }
    

    【讨论】:

      【解决方案2】:

      简单。添加了一个 else if 条件并创建了一个新角色

      【讨论】:

        猜你喜欢
        • 2011-08-23
        • 1970-01-01
        • 1970-01-01
        • 2013-11-13
        • 1970-01-01
        • 2011-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多