Code First Seed Asp.net身份

时间:2016-01-28 02:53:48

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

我正在研究一个已经存在了几个月的项目的新要求。我正在使用Code First(EF6)和Asp.net Identity。我需要在种子方法中添加一个新的用户角色,并将此角色附加到管理员。 如何在种子中向管理员添加新角色? 下面是我的种子方法的代码片段。

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

    }

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

}