种子方法无法将角色分配给用户

时间:2018-08-22 15:53:16

标签: asp.net asp.net-mvc entity-framework

我正在尝试播种数据库,但是当不存在将角色分配给用户的时间时,出现此错误角色SystemAdministrator。我在AspNetRoles表中还有一个名为VariableName的附加字段,因此无法使用rolemanager进行添加。

这是我的种子代码

protected override void Seed(ApplicationDbContext context)
{
    if (!context.AspNetApplications.Any())
    {
        context.AspNetApplications.AddOrUpdate(
            new AspNetApplications()
            {
                Id = "abcd-bcda",
                Name = "AppnameOne",
                Description = "Description",
                SecretKey = GenerateSecretKey(),
                CreatedOn = DateTime.Now,
                UpdatedOn = DateTime.Now
            }
        );
        context.SaveChanges();
    }

    if (!context.Roles.Any())
    {
        context.Roles.AddOrUpdate(
             new AspNetRoles
             {
                 Id = "93547517-f40d-4479-a7f4-73e86d3edddd",
                 Name = "System Administrator",
                 VariableName = "SystemAdministrator",
                 ApplicationId = "abcd-bcda"
             });

        context.SaveChanges();
    }

    if (!context.Users.Any())
    {
        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);
        var user = new ApplicationUser
        {
            Id = "bbccdd-ccbbdd",
            Email = "system@appnameone.com",
            UserName = "system@appnameone.com",
            PhoneNumber = "1234567890"
        };
        userManager.Create(user,"TestP@ssW0RD");
        var userExtended = new AspNetUsersExtendedDetails
        {
            FirstName = "System",
            LastName = "Administrator",
            DateOfBirth = DateTime.Now,
            UserId = "abcd-bcda"
        };
        context.AspNetUsersExtendedDetails.AddOrUpdate(userExtended);
        userManager.AddToRole("bbccdd-ccbbdd", "SystemAdministrator");
        context.SaveChanges();
    }
}

希望有人可以看看这个,让我知道我哪里出问题了? 谢谢。

0 个答案:

没有答案