数据库中的MVC5 Identity Seed用户

时间:2015-05-19 21:01:11

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

我收到一条错误消息:“未找到UserId。”尝试将多个用户植入我的数据库时。

这是我的种子方法:

protected override void Seed(newBestPlay.Models.ApplicationDbContext context)
{
    //  This method will be called after migrating to the latest version.
    InitialCreate create = new InitialCreate();
    create.Down();
    create.Up();
    context.Configuration.LazyLoadingEnabled = true;

    if (!context.Roles.Any(r => r.Name == "Admin"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "Admin" };
        manager.Create(role);
    }

    if (!context.Roles.Any(r => r.Name == "User"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "User" };
        manager.Create(role);
    }

    if (!context.Users.Any(u => u.UserName == "user1"))
    {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser { UserName = "user1", Email = "email1" };
        manager.Create(user, "ChangeItAsap!");
        manager.AddToRole(user.Id, "Admin");
    }

    if (!context.Users.Any(u => u.UserName == "user2"))
    {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser { UserName = "user2", Email = "email2" };
        manager.Create(user, "ChangeItAsap!");
        manager.AddToRole(user.Id, "Admin");
    }
}

在最后一个“manager.AddToRole”行上失败了。我发现第二个用户甚至没有被添加到数据库中,所以它找不到用户。因为它从未被添加过。

2 个答案:

答案 0 :(得分:2)

想出来。它不允许在我的用户名中使用破折号。我的用户名(电子邮件)在域部分中有一个破折号。我不得不加入

this.UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };

进入我的IdentityConfig.cs文件到ApplicationUserManager构造函数中,所以它现在看起来像这样:

public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
            this.UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
        }
.....

答案 1 :(得分:0)

将此添加到种子方法中:

var manager = new UserManager<ApplicationUser>(store);

  manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,

            };